Partition an array based on a condition
Split items into [matching, not matching] in one pass.
function partition(values, predicate) { return values.reduce((groups, value) => (groups[predicate(value) ? 0 : 1].push(value), groups), [[], []]); }
Usage
partition([1, 2, 3, 4, 5], n => n % 2); // → [[1, 3, 5], [2, 4]]
const events = [{ to: 'ana@example.com', status: 'delivered' }, { to: 'rui@example.com', status: 'bounced' }];
const [delivered, other] = partition(events, event => event.status === 'delivered');
other; // → [{ to: 'rui@example.com', status: 'bounced' }]
Know the limits
- The predicate’s result is tested for truthiness: n % 2 puts odd numbers first.
- Object.groupBy (ES2024) is the built-in for more than two groups.
The function above is the code the usage lines run. It does not validate its arguments; add checks where it receives untrusted input.
Source & maintenance
Based on Partition an array based on a condition from the original 1loc collection by Nguyen Huu Phuoc, with TangSY. Copyright (c) 2020 phuoc-ng. MIT licensed.
Documented as a reference with executed usage lines. Original MDX retained as inert source evidence.
Maintained by Oveyon. Original source commit: 14b481cf60df. This edition’s file: contents/partition-an-array-based-on-a-condition.mdx in akamind/1loc, commit 0a77f131b22d. Read the license.
Keep exploring
- Clone an array — Create a new array without copying the objects inside it.
- Remove duplicate values — Keep the first occurrence of each value, in its original order.
- Flatten a nested array — Turn a nested array into one sequence of values.