Get all subsets of length k from an array in JavaScript
Advanced · 4 min read
Say a pizza shop lets you pick two toppings from a list of five. How many different pizzas can you order, and what are they? That question, "every way to choose k things from a list", comes up all the time: pairing players for matches, testing every pair of settings, building a quiz from a bank of questions.
In this tutorial you will write combinations(items, k). Give it [1, 2, 3] and 2, and it returns [[1, 2], [1, 3], [2, 3]]. You need to know arrays, functions and map. The one big idea, recursion, is explained from the start.
Combinations, not permutations
A subset is a group of items where order does not matter. [1, 2] and [2, 1] are the same pair, so only one of them belongs in the answer. Groups of this kind are called combinations.
If order did matter, you would be listing permutations, and there would be more of them. From [1, 2, 3], choosing 2:
combinations: [1,2] [1,3] [2,3] 3 of them
permutations: [1,2] [1,3] [2,1] [2,3] [3,1] [3,2] 6 of them
This exercise wants the first list. Inside each subset, items keep the order they had in the input.
Recursion in one minute
A recursive function solves a problem by calling itself on a smaller version of the same problem. It needs a base case: a small input it can answer straight away, so the calls eventually stop.
function countdown(n) {
if (n === 0) return 'liftoff'; // base case
return n + ' ' + countdown(n - 1); // smaller problem
}
console.log(countdown(3)); // '3 2 1 liftoff'
Each call hands a smaller n to the next one, until n reaches 0.
Here is the exercise. Have a go on your own if you like: the hints open one at a time. Otherwise, read on and we will build it together.
21 Subsets of a fixed length
hard[1, 2, 3] with length 2 should give [[1,2],[1,3],[2,3]]. Order within each subset follows the input; subsets are not repeated.
Stuck? Three hints, smallest first
- 1. These are combinations, not permutations:
[1,2]and[2,1]are the same subset. - 2. Recurse: either take the first element and choose
k-1more, or skip it and choosek. - 3. The count is
n! / (k!(n-k)!), which is the binomial coefficient.
Step 1: take it or leave it
Look at the first item in the list. Every subset either contains it or doesn't. That splits the problem in two:
- Take it: put the first item in, then choose
k - 1more from the rest. - Leave it: skip the first item, and choose all
kfrom the rest.
For [1, 2, 3] with k = 2: taking 1 means choosing one more from [2, 3], which gives [1, 2] and [1, 3]. Leaving 1 means choosing two from [2, 3], which gives [2, 3]. Together that is the full answer.
Both halves are the same question on a shorter list, which is exactly what recursion needs.
Step 2: the two base cases
The calls stop in two situations:
k === 0: there is exactly one way to choose nothing, the empty subset. So return[[]], a list holding one empty array.k > items.length: you can't choose more items than there are. There is no way at all, so return[].
function baseCases(items, k) {
if (k === 0) return [[]];
if (k > items.length) return [];
return 'needs the recursive step';
}
console.log(baseCases([1, 2], 0).length); // 1: one empty subset
console.log(baseCases([1, 2], 3).length); // 0: no subsets
Keep the difference in mind: [[]] has one thing in it, [] has nothing.
Step 3: the recursive split
Now write the take-it-or-leave-it split. const [first, ...rest] = items pulls the first item out and puts everything after it in rest. Inside map, [first, ...c] builds a new array with first in front of each smaller subset c.
function combinations(items, k) {
if (k === 0) return [[]];
if (k > items.length) return [];
const [first, ...rest] = items;
const withFirst = combinations(rest, k - 1).map((c) => [first, ...c]);
const withoutFirst = combinations(rest, k);
return [...withFirst, ...withoutFirst];
}
console.log(JSON.stringify(combinations([1, 2, 3], 2))); // '[[1,2],[1,3],[2,3]]'
console.log(JSON.stringify(combinations([1, 2, 3], 1))); // '[[1],[2],[3]]'
console.log(JSON.stringify(combinations([1, 2, 3], 3))); // '[[1,2,3]]'
JSON.stringify turns the nested arrays into text so you can see them all at once. Because the "take it" results come first, every subset keeps the input order.
Step 4: the base case people get wrong
It is tempting to think "choosing nothing gives nothing" and return [] when k is 0. Try it:
function broken(items, k) {
if (k === 0) return []; // looks reasonable, but wrong
if (k > items.length) return [];
const [first, ...rest] = items;
const withFirst = broken(rest, k - 1).map((c) => [first, ...c]);
const withoutFirst = broken(rest, k);
return [...withFirst, ...withoutFirst];
}
console.log(JSON.stringify(broken([1, 2, 3], 2))); // '[]'
Every answer is empty. The deepest calls return [], and mapping over an empty array gives another empty array, all the way back up. With [[]], the map has one empty subset to put first in front of, and the results grow from there.
Step 5: refuse a bad k
A k of -1 or 1.5 makes no sense. The answer returns no subsets for those, before any other check:
const okK = (k) => Number.isInteger(k) && k >= 0;
console.log(okK(2)); // true
console.log(okK(-1)); // false
console.log(okK(1.5)); // false
In the full function this becomes if (!Number.isInteger(k) || k < 0) return []; as the first line.
Step 6: check the count
There is a formula for how many combinations to expect, written C(n, k), "n choose k". The answer's choose helper works it out without big factorials:
const choose = (n, k) => {
let out = 1;
for (let i = 1; i <= k; i++) out = (out * (n - k + i)) / i;
return Math.round(out);
};
console.log(choose(3, 2)); // 3
console.log(combinations([1, 2, 3, 4, 5], 3).length); // 10
console.log(choose(5, 3)); // 10
The function and the formula agree. One more check: every item is either in a subset or not, so adding up the counts for every k from 0 to n gives 2 to the power n. For three items, 1 + 3 + 3 + 1 is 8.
The full solution
The panel has combinations with its input check, a permutations function for contrast, and choose. It prints the example, the six permutations, the count for 5 choose 3, and every subset of [1, 2, 3]. Press Run to see the output.
/* Two base cases carry the whole function:
k === 0 one way to choose nothing: the empty subset
k > remaining no way to choose that many */
function combinations(items, k) {
if (!Number.isInteger(k) || k < 0) return [];
if (k === 0) return [[]];
if (k > items.length) return [];
const [first, ...rest] = items;
// Take the first, then choose k-1 from the rest; or skip it and choose k.
const withFirst = combinations(rest, k - 1).map((c) => [first, ...c]);
const withoutFirst = combinations(rest, k);
return [...withFirst, ...withoutFirst];
}
// Permutations, for contrast: order matters, so there are more of them.
function permutations(items, k) {
if (k === 0) return [[]];
return items.flatMap((item, i) =>
permutations([...items.slice(0, i), ...items.slice(i + 1)], k - 1).map((p) => [item, ...p]));
}
const choose = (n, k) => {
let out = 1;
for (let i = 1; i <= k; i++) out = (out * (n - k + i)) / i;
return Math.round(out);
};
console.log('combinations([1,2,3], 2) =', JSON.stringify(combinations([1, 2, 3], 2)));
console.log('the expected value = [[1,2],[1,3],[2,3]]');
console.log('permutations([1,2,3], 2) =', JSON.stringify(permutations([1, 2, 3], 2)), '<- order matters, so six');
console.log('combinations of 5 choose 3:', combinations([1, 2, 3, 4, 5], 3).length, '= C(5,3) =', choose(5, 3));
console.log('every subset of [1,2,3]:', [0, 1, 2, 3].map((k) => JSON.stringify(combinations([1, 2, 3], k))).join(' '));
Output
19 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 19 of them and prints ok for each.
That output is the proof, and the build fails if a single check fails.
test("the example in the question", combinations([1, 2, 3], 2), [[1, 2], [1, 3], [2, 3]]);
test('three of them', combinations([1, 2, 3], 2).length, 3);
test('which is C(3,2)', combinations([1, 2, 3], 2).length, choose(3, 2));
test('choosing 0 gives one empty subset', combinations([1, 2, 3], 0), [[]]);
test('choosing all gives one subset, the whole list', combinations([1, 2, 3], 3), [[1, 2, 3]]);
test('choosing more than there are gives none', combinations([1, 2], 3), []);
test('choosing 1 gives each element alone', combinations([1, 2, 3], 1), [[1], [2], [3]]);
test('from an empty list, only the empty subset', combinations([], 0), [[]]);
test('and nothing if you want any', combinations([], 1), []);
test('a negative length gives nothing', combinations([1, 2], -1), []);
test('C(5,3) is 10', combinations([1, 2, 3, 4, 5], 3).length, 10);
test('and C(6,3) is 20', combinations([1, 2, 3, 4, 5, 6], 3).length, 20);
test('every subset has the requested length', combinations([1, 2, 3, 4, 5], 3).every((c) => c.length === 3), true);
test('order inside each subset follows the input', combinations([3, 1, 2], 2), [[3, 1], [3, 2], [1, 2]]);
test('no subset is repeated', new Set(combinations([1, 2, 3, 4], 2).map(String)).size, 6);
test('permutations of the same choice are more numerous', permutations([1, 2, 3], 2).length, 6);
test('exactly k! times as many', permutations([1, 2, 3], 2).length / combinations([1, 2, 3], 2).length, 2);
test('and for k = 3', permutations([1, 2, 3], 3).length / combinations([1, 2, 3], 3).length, 6);
test('the total over all k is 2^n', [0, 1, 2, 3].reduce((n, k) => n + combinations([1, 2, 3], k).length, 0), 2 ** 3);
The recursion is the classic take-it-or-leave-it split: for each element, either include it and choose k-1 more from what remains, or exclude it and choose k. Both base cases are load-bearing, and the first is the one people get wrong — k === 0 returns [[]], an array containing one empty subset, not []. Return [] there and the whole function produces nothing, because there is nothing for the map to build on.
Combinations against permutations is the distinction worth being sure about: [1,2] and [2,1] are the same subset and different orderings. The assertion that permutations are exactly k! times as many is a good structural check on both functions at once.
Summing the counts over every k gives 2^n, which is the last assertion — a nice independent confirmation, since every element is either in a subset or not.
Common mistakes
- Returning
[]whenkis 0. It wipes out every result. There is one way to choose nothing, so return[[]]. - Listing permutations instead.
[1, 2]and[2, 1]are the same subset. If you get six pairs from three items, order is sneaking in. - Using
items.shift()to take the first item.shiftchanges the caller's array.const [first, ...rest] = itemsleaves it alone.
Try it yourself
- List every pair of colors from
['red', 'green', 'blue']. You should get three pairs. - Check that
combinationsof six items, choosing 3, giveschoose(6, 3), which is 20. - Write
allSubsets(items)that joins the results for everykfrom 0 toitems.length. For three items it should return 8 subsets.