DEV Community

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

Posted on • Updated on

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)