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]]
expect(partition([1, 2, 3, 4, 5], (n) => n % 2 === 0)).toEqual([[2, 4], [1, 3, 5]]);
expect(partition([5, 1, 4, 2, 3], (n) => n > 2)).toEqual([[5, 4, 3], [1, 2]]);
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]]);
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);
expect(partition([], () => true)).toEqual([[], []]);
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]);
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).
I'm here to help with Partition an array. I give hints, never the solution, so you get to solve it yourself. Ask for a hint, select code to ask about it, or press Ask Tuto why on a failing test.
Your first 3 answers need no account. for free to keep asking.