Partition an array by a condition in JavaScript
Advanced · 4 min read
Partitioning a list means splitting it in two: the items that pass a test, and the items that fail. Paid and unpaid invoices, passing and failing grades, valid and invalid form fields. You need both halves, and you want each item to be checked only once.
JavaScript has no built-in partition, so in this tutorial you will write one. You will compare it with the common two-filter approach, count how much work each does, and then extend the idea to more than two groups. You should know arrays, arrow functions and filter. Destructuring and Map are explained below.
The two-filter way
The usual first answer is to filter twice, once for each half:
const odd = (n) => n % 2 === 1;
const nums = [1, 2, 3, 4];
console.log(nums.filter(odd)); // [ 1, 3 ]
console.log(nums.filter((n) => !odd(n))); // [ 2, 4 ]
It works, but it has two weak spots. It walks the list twice, so the test runs twice for every item. And the two tests have to stay exact opposites. If someone edits one and forgets the other, an item can end up in both halves or in neither.
Destructuring a pair
A function can return two things by returning an array of two items. The caller then unpacks it with destructuring, naming each position:
const pair = () => [[1, 3], [2, 4]];
const [odds, evens] = pair();
console.log(odds); // [ 1, 3 ]
console.log(evens); // [ 2, 4 ]
The caller picks the names, so the same function can give [paid, unpaid] in one place and [valid, invalid] in another.
Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.
49 Partition a list in two
hardSplit a list into the elements that pass a test and the elements that fail, in one pass. Then extend the idea to more than two groups.
Stuck? Three hints, smallest first
- 1. Choose which array to push into:
(keep(x) ? yes : no).push(x). - 2. Return the pair as an array so the caller can destructure it.
- 3. Two calls to
filterwould do the same job with twice the predicate calls.
Step 1: one pass, two arrays
Make two empty arrays. For each item, run the test once and push the item into the right one:
function partition(xs, keep) {
const yes = [];
const no = [];
xs.forEach((x, i) => (keep(x, i) ? yes : no).push(x));
return [yes, no];
}
console.log(partition([1, 2, 3, 4], (n) => n % 2 === 1)); // [ [ 1, 3 ], [ 2, 4 ] ]
The interesting part is (keep(x, i) ? yes : no).push(x). The ? : picks which array to use: yes if the test passes, no if it doesn't. Then .push(x) is called on whichever one was picked. It is a short way of writing an if with two push calls.
The test also receives the index i, just like the function you pass to filter.
Step 2: check the halves
function partition(xs, keep) {
const yes = [];
const no = [];
xs.forEach((x, i) => (keep(x, i) ? yes : no).push(x));
return [yes, no];
}
const [pass, fail] = partition([1, 2, 3, 4], (n) => n % 2 === 1);
console.log(pass, fail); // [ 1, 3 ] [ 2, 4 ]
console.log(partition([4, 1, 3, 2], (n) => n > 2)); // [ [ 4, 3 ], [ 1, 2 ] ]
console.log(partition(['a', 'b', 'c'], (_, i) => i % 2 === 0)); // [ [ 'a', 'c' ], [ 'b' ] ]
console.log(partition([1, 2], () => false)); // [ [], [ 1, 2 ] ]
console.log(partition([], () => true)); // [ [], [] ]
Each half keeps the input's order: 4 comes before 3 because it came first. The underscore in (_, i) is a name for "the item, which we don't need here". When nothing passes, the first half is simply empty, and an empty input gives two empty halves.
Step 3: count the work
To see the difference from the two-filter way, count how many times each version calls its test:
function partition(xs, keep) {
const yes = [];
const no = [];
xs.forEach((x, i) => (keep(x, i) ? yes : no).push(x));
return [yes, no];
}
let onePass = 0;
partition([1, 2, 3, 4], (n) => { onePass++; return n % 2 === 1; });
let twoPasses = 0;
const odd = (n) => { twoPasses++; return n % 2 === 1; };
[1, 2, 3, 4].filter(odd);
[1, 2, 3, 4].filter((n) => !odd(n));
console.log(onePass, twoPasses); // 4 8
Four calls against eight. For a cheap test like "is it odd?" that hardly matters. For a test that does real work, such as checking a date or looking something up, it is half the cost. And there is only one test to keep correct.
Step 4: more than two groups
Sometimes there are more than two outcomes, like sorting numbers by their remainder after dividing by 3. Then a yes-or-no test isn't enough. Use a function that returns a key for each item, and collect items by key in a Map. A Map stores key and value pairs, keeps keys as they are (numbers stay numbers), and remembers the order they were first added.
const partitionBy = (xs, keyOf) => xs.reduce((m, x) => {
const key = keyOf(x);
return m.set(key, [...(m.get(key) ?? []), x]);
}, new Map());
const groups = partitionBy([1, 2, 3, 4, 5, 6], (n) => n % 3);
console.log(groups); // Map(3) { 1 => [ 1, 4 ], 2 => [ 2, 5 ], 0 => [ 3, 6 ] }
For each item, m.get(key) ?? [] reads the group so far, or an empty array if this key is new. The new item is added to the end, and set stores the result. set returns the map, which reduce passes on to the next item.
The keys come out as 1, 2, 0, in the order they first appeared: 1 gives key 1, 2 gives key 2, and 3 gives key 0.
The full solution
The panel has partition and partitionBy, runs the examples above, and prints the call counts for one pass and two filters. Press Run and compare the counts.
function partition(xs, keep) {
const yes = [];
const no = [];
xs.forEach((x, i) => (keep(x, i) ? yes : no).push(x));
return [yes, no];
}
// More than two outcomes needs a key rather than a boolean.
const partitionBy = (xs, keyOf) => xs.reduce((m, x) => {
const key = keyOf(x);
return m.set(key, [...(m.get(key) ?? []), x]);
}, new Map());
let onePass = 0;
partition([1, 2, 3, 4], (n) => { onePass++; return n % 2 === 1; });
let twoPasses = 0;
const odd = (n) => { twoPasses++; return n % 2 === 1; };
[1, 2, 3, 4].filter(odd);
[1, 2, 3, 4].filter((n) => !odd(n));
const [pass, fail] = partition([1, 2, 3, 4], (n) => n % 2 === 1);
const sizes = [...partitionBy([1, 2, 3, 4, 5, 6], (n) => n % 3)].map(([k, g]) => [k, g.length]);
console.log('odd / even :', partition([1, 2, 3, 4], (n) => n % 2 === 1));
console.log('destructured :', pass, fail);
console.log('by index :', partition(['a', 'b', 'c'], (_, i) => i % 2 === 0));
console.log('nothing passes:', partition([1, 2], () => false));
console.log('predicate calls: partition', onePass, ' two filters', twoPasses);
console.log('three ways by n % 3:', sizes);
Output
9 checks that prove this answer
You do not have to read these. They are part of the answer panel above, so pressing
Run there executes all 9 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test('the list splits into pass and fail', partition([1, 2, 3, 4], (n) => n % 2 === 1), [[1, 3], [2, 4]]);
test('the two halves account for every element', pass.length + fail.length, 4);
test('order inside each half follows the input', partition([4, 1, 3, 2], (n) => n > 2), [[4, 3], [1, 2]]);
test('nothing passing leaves the first half empty', partition([1, 2], () => false), [[], [1, 2]]);
test('an empty input gives two empty halves', partition([], () => true), [[], []]);
test('the predicate receives the index', partition(['a', 'b', 'c'], (_, i) => i % 2 === 0), [['a', 'c'], ['b']]);
test('partition calls the predicate once per element', onePass, 4);
test('while filtering twice calls it twice per element', twoPasses, 8);
test('a key function gives as many groups as it has keys', sizes, [[1, 2], [2, 2], [0, 2]]);
partition is missing from the standard library and worth adding to your own, because the alternative is a pair of filter calls whose predicates must stay exact negations of each other. The assertions count the cost: four predicate calls against eight, and one place to change instead of two.
Returning an array rather than { yes, no } is deliberate — it destructures positionally, so the caller names the halves whatever suits them. The Map version generalises to any number of groups and keeps non-string keys intact, which is exercise 33's lesson applied here: the keys 1, 2 and 0 stay numbers and stay in the order first encountered.
Common mistakes
- Filtering twice with two separate tests. The tests can drift apart, and every item is checked twice. Partition once.
- Returning an object and then guessing its field names. Returning
[yes, no]lets the caller choose names with destructuring. - Grouping by key in a plain object. Keys become strings, so
1and'1'merge. AMapkeeps them apart.
Try it yourself
- Partition a list of words into those shorter than five letters and the rest.
- Use
partitionwith the index to split a list into items at even and odd positions. - Use
partitionByto group a list of names by their first letter.