javascript - How to filter to multiple paths using functional programming -
i have following pseudo-code:
let array = getdata(); array.filter(x => condition1(x)).dosomething1... array.filter(x => condition2(x)).dosomething2... array.filter(x => condition3(x)).dosomething3... obviously not efficient because iterates array 3 times.
i wondering if there way like:
array.filtermany([ x => condition1(x).dosomething1..., x => condition2(x).dosomething2..., x => condition3(x).dosomething3... ]) so array gets iterated once?
you can use array reduce functionality.
for example:
const arr = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]; const split = arr.reduce(([odd, even], current) => { if (current % 2 === 0) { even.push(current); } else { odd.push(current); } return [odd, even]; }, [[], []]); console.log('odd / even', split); wiki
Comments
Post a Comment