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.
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 equalityWhat 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.
- 1.splits matches from non-matches
- 2.passes the index as the second argument
- 3.returns two empty arrays for empty input
- 4.puts everything in the first half when all match
- 5.treats truthy values as a match
These assertions run in your browser the moment you hit Run. Pass all of them to claim the XP.
Discussion
Sign in to postNo comments yet. Be the first to say something.