Partition an array based on a condition

Split items into [matching, not matching] in one pass.

JavaScriptNode.js & browsers Version 1.0.0 · MIT · .md

partition-an-array-based-on-a-condition.js
function partition(values, predicate) { return values.reduce((groups, value) => (groups[predicate(value) ? 0 : 1].push(value), groups), [[], []]); }

Usage

usage.js
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' }]

Lines marked → were executed in Node.js 22 and in headless Chromium, and each result was compared with the value shown. Lines marked e.g. are illustrative.

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.

Usage lines executed in Node.js 22 and headless Chromium; no external services · reviewed October 28, 2026.

Keep exploring

Type two or more characters. Try “duplicate”, “webhook” or “retry”.