I have the 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 this is not efficient because it iterates the array 3 times.
I was wondering if I there is a way to do something like:
array.filterMany([
x => condition1(x).doSomething1...,
x => condition2(x).doSomething2...,
x => condition3(x).doSomething3...
])
So that the array gets iterated only 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);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments