AniUI Academy

Partition an array in one pass

easyArrays & Objects+150 XPPractice

Writing items.filter(isDone) and items.filter(x => !isDone(x)) walks the array twice and calls the predicate twice per item. When the predicate is expensive, or when you want the two halves to stay in sync, one pass is better.

Implement partition(items, predicate). Call predicate(item, index) for each item, where index is its position in the input array. Return an array of exactly two arrays: the first holds every item for which the predicate returned a truthy value, the second holds the rest. Both keep the items in their original relative order. An empty input returns [[], []]. Never modify items.

Arguments

itemsArray
The input list to split.
predicate(item, index) => boolean
Called for each item. Truthy returns go in the first array, everything else in the second.

Returns

[Array, Array] — A two-element array: matches first, non-matches second. Both preserve original order.

Examples

partition([1, 2, 3, 4], (n) => n % 2 === 0);
// [[2, 4], [1, 3]]
partition(["a", "b", "c", "d"], (_, index) => index % 2 === 0);
// [["a", "c"], ["b", "d"]] — the predicate gets the index too

partition([0, 1, "", "x"], (value) => value);
// [[1, "x"], [0, ""]] — truthiness, not strict equality

What it has to do

  • Return exactly two arrays: matches first, non-matches second.
  • Call the predicate with (item, index).
  • Judge by truthiness, not by strict equality with true.
  • Preserve the original order within each half.
  • Return [[], []] for an empty input array, and do not mutate the input.

Stuck? The javascript course covers everything this challenge needs.

Try it yourself
Loading playground...
5 tests · +150 XP

Discussion

Sign in to post
Sign in to join the conversation.Sign in

No comments yet. Be the first to say something.