partitionLoading saved progress…

partition

partition splits an array into two groups: the elements that pass a predicate and the elements that fail it. It's filter that keeps both halves — the matches and the rejects — instead of throwing one away. Reach for it when you need "the active users and the inactive ones," not just one side.

Implement partition(arr, predicate, thisArg). Return a pair [pass, fail]: passing elements first, failing elements second, each in the original relative order. Do it in a single pass, calling the predicate once per element.

Signature

function partition(arr, predicate, thisArg) {
  // returns [pass, fail]: [elements where predicate is truthy,
  //                        elements where it is falsy]
}

Examples

partition([1, 2, 3, 4], (n) => n % 2 === 0); // [[2, 4], [1, 3]]
const [adults, minors] = partition(people, (p) => p.age >= 18);
partition([2, 4], (n) => n % 2 === 0); // [[2, 4], []] — all pass

Notes

  • Pass first, fail second — the return is always [passing, failing], in that order.
  • Order preserved — within each group, elements keep their original relative order.
  • Single pass — call the predicate exactly once per element; don't run it twice.
  • Truthiness — any truthy result counts as pass, not just literal true.
  • Predicate args(value, index, array), with thisArg as this. Don't mutate the input; return two new arrays.
Loading editor…