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

javascript - how to pass array into chain of functions

itayp1 profile image Itayp1 Updated on ・1 min read

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 }
]

Posted on by:

Discussion

markdown guide