Partition an array into two groups
Split an array into the items that pass a test and the items that fail it, in one pass, and compare a reduce partition with Object.groupBy. Node.js 21.
filter(test) and filter(not(test)) run the test twice for every item. A partition does it once, and Node.js 21 added Object.groupBy, which gives you one.
const partition = (items, test) =>
items.reduce(
([pass, fail], item, index) => (test(item, index) ? [[...pass, item], fail] : [pass, [...fail, item]]),
[[], []],
);
const [even, odd] = partition([1, 2, 3, 4, 5, 6], (n) => n % 2 === 0);
console.log(even, odd);
const groups = Object.groupBy([1, 2, 3, 4, 5, 6], (n) => (n % 2 === 0 ? 'even' : 'odd'));
console.log(groups);
console.log(Object.groupBy([2, 4], (n) => (n % 2 === 0 ? 'even' : 'odd')).odd);[ 2, 4, 6 ] [ 1, 3, 5 ]
[Object: null prototype] { odd: [ 1, 3, 5 ], even: [ 2, 4, 6 ] }
undefinedThe reduce version returns a pair of arrays and runs the test one time per item. It is easy to read, but each step copies both arrays with a spread, so the work grows with the square of the length, and a loop that calls push is the right form for a big array. Object.groupBy with a function that returns 'even' or 'odd' gives an object with two keys, and the order of the keys is the order of first appearance, so odd came first here because 1 is odd. A key with no items is absent, not an empty array, and the last line prints undefined for odd when the input has only even numbers. The grouping is defined in the specification for Object.groupBy.
So read the result with a default, groups.odd ?? []. The returned object has a null prototype, and printing it shows [Object: null prototype]. Code that runs on Node.js 20 and older needs the reduce or a loop.