Skip to the code
cf.

Partition an array

Write partition(array, predicate). It returns a pair of new arrays, [pass, fail]. pass holds the items for which predicate returned a truthy value, and fail holds the rest. Both keep the items in their original order.

Call predicate once for each item, with the three arguments filter passes: the item, its index, and the array.

An empty array gives [[], []]. array itself never changes.

const [even, odd] = partition([1, 2, 3, 4, 5], (n) => n % 2 === 0);
even; // [2, 4]
odd;  // [1, 3, 5]
 
partition(["a", "", "b", null], (value) => value); // [["a", "b"], ["", null]]

What the tests check

  1. splits the items by the predicate
    expect(partition([1, 2, 3, 4, 5], (n) => n % 2 === 0)).toEqual([[2, 4], [1, 3, 5]]);
    
  2. keeps the original order in both arrays
    expect(partition([5, 1, 4, 2, 3], (n) => n > 2)).toEqual([[5, 4, 3], [1, 2]]);
    
  3. counts any truthy result as a pass
    expect(partition([0, 1, "", "a", null, []], (value) => value)).toEqual([[1, "a", []], [0, "", null]]);
    expect(partition([1, 2, 3], (n) => n % 2)).toEqual([[1, 3], [2]]);
    
  4. calls predicate once per item, with the item, its index, and the array
    const input = ["a", "b", "c"];
    const check = spy(() => true);
    partition(input, check);
    expect(check).toHaveBeenCalledTimes(3);
    expect(check.calls[1].args[0]).toBe("b");
    expect(check.calls[1].args[1]).toBe(1);
    expect(check.calls[1].args[2]).toBe(input);
    
  5. returns two empty arrays for an empty array
    expect(partition([], () => true)).toEqual([[], []]);
    
  6. returns new arrays and leaves the original alone
    const input = [1, 2, 3];
    const [pass, fail] = partition(input, () => true);
    expect(pass).not.toBe(input);
    expect(pass).toEqual([1, 2, 3]);
    expect(fail).toEqual([]);
    partition(input, (n) => n > 1);
    expect(input).toEqual([1, 2, 3]);
    

Learn more

solution.jsSaved in this browser

Run tests runs every test on your code, here in your browser. The problem is solved when they all pass.

Ctrl + Enter runs the tests (⌘ + Enter on a Mac).