This is a pattern to split the values from an array into two groups based on a condition, if is truthy the corresponding element belongs to the first group, otherwise it belongs to the second group.
This is a pattern to split the values from an array into two groups based on a condition, if is truthy the corresponding element belongs to the first group, otherwise it belongs to the second group, we are going to use two method from the Array
, the reduce
and the push
to add the elements to groups.
I found myself filtering an array of items to get all items that matched a certain condition, then doing that again for a different condition. That meant looping over an array twice but I could have just done it once with this pattern.
const values = [1, 15, 8, 32, 23, 2];
const [truthyValues, falseyValues] = values.reduce((accumulator, value) => {
if (value > 10) {
accumulator[0].push(value);
} else {
accumulator[1].push(value);
}
return accumulator;
}, [[], []]);
console.log(truthyValues);
// expected output: [15, 32, 23]
console.log(falseyValues);
// expected output: [1, 8, 2]
We can improve this by implementing a filter function
const bifurcate = (arr, filter) =>
arr.reduce((accumulator, value) => {
accumulator[filter(value) ? 0 : 1].push(value);
return accumulator;
}, [[], []]);
const values = [1, 15, 8, 32, 23, 2];
const [truthyValues, falseyValues] = bifurcate(values, v => v > 10);
console.log(truthyValues);
// expected output: [15, 32, 23]
console.log(falseyValues);
// expected output: [1, 8, 2]