Skip to content
jshacks.dev
Fundamentals

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.

2 min read
Summarize in AI

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.

JavaScript
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);
Text
[ 2, 4, 6 ] [ 1, 3, 5 ]
[Object: null prototype] { odd: [ 1, 3, 5 ], even: [ 2, 4, 6 ] }
undefined

The 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.

Taggednode 24
Share

More snippets

Fundamentals

Sort dates in an array

Sort an array of Date objects by subtracting them, and see why the default sort orders dates by weekday name. Works in every Node.js release.

1 min read
Fundamentals

Sort by multiple keys

Sort records by several keys in one comparator with toSorted, falling through to the next key when the first ties. Needs Node.js 20, stable since ES2019.

1 min read
Fundamentals

Get a random item from an array

Pick a random item from an array with Math.random, and see why rounding the index instead of flooring it makes the middle item twice as likely. Node.js 18.

2 min read

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.