750 B
750 B
title, type, language, tags, cover, dateModified
| title | type | language | tags | cover | dateModified | |
|---|---|---|---|---|---|---|
| Bifurcate array based on function | snippet | javascript |
|
canoe | 2020-11-01T20:50:57+02:00 |
Splits values into two groups, based on the result of the given filtering function.
- Use
Array.prototype.reduce()andArray.prototype.push()to add elements to groups, based on the value returned byfnfor each element. - If
fnreturns a truthy value for any element, add it to the first group, otherwise add it to the second group.
const bifurcateBy = (arr, fn) =>
arr.reduce((acc, val, i) => (acc[fn(val, i) ? 0 : 1].push(val), acc), [
[],
[],
]);
bifurcateBy(['beep', 'boop', 'foo', 'bar'], x => x[0] === 'b');
// [ ['beep', 'boop', 'bar'], ['foo'] ]