AniUI Academy
easy+150 XPPractice

Partition an array in one pass

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.

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.

Your workspace

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.