DEV Community

Cover image for javascript - how to pass array into chain of functions
Itayp1
Itayp1

Posted on • Edited on

1 2

javascript - how to pass array into chain of functions

chain functions

lets asume that we have an array of object
and you want to make few operation on the array like
filter , map , sort
so one option will be straightforward
run each time on every operation

const arr = [{ name: itay, age: 10 }, { name: sam, age: 20 }, { name: jett, age: 30 }, { name: bob, age: 40 }]


//filter  the obkect with age under 10
const filtering = ({ age }) => age > 10
filterdArr = arr.filter(filtering)

// abount the sorting - if the function return negetive value then a will be befora b
//and if the funtion  return positive number then b will be before a 
const sorting = (a, b) => a.age - b.age
sortedArr = filterdArr.sort(sorting)

//refactor the object , changed age to myAge
const mapping = ({ name, age }) => ({ name, myAge: age })
mapedArr = sortedArr.map(mapping)

console.log(mapedArr)


the second option will be to chain the funtions
like that

console.log(
    arr.filter(filtering)
        .sort(sorting)
        .map(mapping))

and the result will be the same
[
{ name: 'jett', myAge: 30 },
{ name: 'bob', myAge: 40 },
{ name: 'sam', myAge: 55 }
]

Top comments (0)

SurveyJS custom survey software

JavaScript Form Builder UI Component

Generate dynamic JSON-driven forms directly in your JavaScript app (Angular, React, Vue.js, jQuery) with a fully customizable drag-and-drop form builder. Easily integrate with any backend system and retain full ownership over your data, with no user or form submission limits.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay