Emmanuel Akinfulubi

JavaScriptArray

Generate all permutations of an array in JavaScript

Advanced · 4 min read

A permutation is one way to arrange a list in order. [1, 2, 3] has six: 123, 132, 213, 231, 312 and 321. Generating them all is a classic exercise in recursion, and it comes up whenever a problem says "try every order": seating plans, puzzle solvers, testing that code works whatever order its inputs arrive in.

In this tutorial you will write permutations in a few lines, check that it produces the right number of results, and then see why "try every order" stops being practical very quickly. You should know arrays, arrow functions, slice and the spread syntax .... Recursion and flatMap are explained below.

Thinking about it by hand

How would you list every order of 1, 2 and 3 on paper? Pick what goes first. Then arrange whatever is left.

Output

1 first, then every order of 2, 3:  1 2 3,  1 3 2
2 first, then every order of 1, 3:  2 1 3,  2 3 1
3 first, then every order of 1, 2:  3 1 2,  3 2 1

Notice that "every order of what's left" is the same problem again, only smaller. That is the sign that recursion fits.

Recursion in one paragraph

A recursive function calls itself on a smaller version of its input. It needs a base case, a small input it can answer directly, so the calls stop. Factorial is the classic example: the factorial of 4, written 4!, is 4 × 3 × 2 × 1, which is 4 times the factorial of 3.

JavaScript

const factorial = (n) => (n <= 1 ? 1 : n * factorial(n - 1));
console.log(factorial(3)); // 6
console.log(factorial(4)); // 24

Factorial matters here for a second reason: a list of n different values has exactly n! permutations. Three values have 6, four have 24.

Here is the exercise. Try it yourself first if you like, or read on and we will build it step by step.

50 Every permutation

hard

Produce every ordering of [1, 2, 3]. Then check the count against n! and work out how far this can be pushed.

Stuck? Three hints, smallest first
  1. 1. Pick each element in turn as the first, and permute what is left.
  2. 2. flatMap is the right combinator: one input element produces many results.
  3. 3. The base case is a list of one — and the empty list has exactly one ordering, the empty one.

Step 1: everything except one item

For each choice of first item, you need the rest of the list without it. Two slices joined by spread do that: everything before index i, then everything after it.

Step 1

const xs = [1, 2, 3];
const i = 1;
const rest = [...xs.slice(0, i), ...xs.slice(i + 1)];

console.log(rest); // [ 1, 3 ]
console.log(xs);   // [ 1, 2, 3 ]

The original list is untouched, because slice makes copies.

Step 2: flatMap

Each choice of first item produces a whole batch of results, and we want them all in one list. flatMap is map followed by flattening one level, so batches get joined together:

Step 2

console.log([1, 2].map((n) => [n, n * 10]));     // [ [ 1, 10 ], [ 2, 20 ] ]
console.log([1, 2].flatMap((n) => [n, n * 10])); // [ 1, 10, 2, 20 ]

Step 3: the recursive function

Now say the plan from the hand-worked example in code. For each item v at index i, find every permutation of the rest, and put v in front of each one:

Step 3

function permutations(xs) {
  if (xs.length <= 1) return [xs.slice()];
  return xs.flatMap((v, i) => {
    const rest = [...xs.slice(0, i), ...xs.slice(i + 1)];
    return permutations(rest).map((tail) => [v, ...tail]);
  });
}

console.log(permutations([1, 2, 3]).map((p) => p.join('')));
// [ '123', '132', '213', '231', '312', '321' ]

The base case is a list of zero or one items. It has exactly one arrangement, itself, so the function returns a list holding one copy of it. The .map((p) => p.join('')) is only there to print each result compactly.

The first result is always the input order, since it picks the first item, then the first of the rest, and so on.

Step 4: the base case trap

What should permutations([]) return? It is tempting to say "nothing", so []. Watch what that does:

Step 4

function broken(xs) {
  if (xs.length === 0) return [];
  return xs.flatMap((v, i) => {
    const rest = [...xs.slice(0, i), ...xs.slice(i + 1)];
    return broken(rest).map((tail) => [v, ...tail]);
  });
}

console.log(broken([1, 2, 3])); // []

Every call eventually reaches an empty rest. If that returns no arrangements, there is nothing to put v in front of, so the call above returns nothing too, and so on all the way up. The whole answer is empty.

The right answer is that there is exactly one way to arrange nothing: the empty arrangement. So permutations([]) is [[]], a list holding one empty list. The working version gets that from [xs.slice()].

Step 5: check the count

Step 5

function permutations(xs) {
  if (xs.length <= 1) return [xs.slice()];
  return xs.flatMap((v, i) => {
    const rest = [...xs.slice(0, i), ...xs.slice(i + 1)];
    return permutations(rest).map((tail) => [v, ...tail]);
  });
}
const factorial = (n) => (n <= 1 ? 1 : n * factorial(n - 1));

const four = permutations([1, 2, 3, 4]);
console.log(four.length, factorial(4));                 // 24 24
console.log(new Set(four.map((p) => p.join(','))).size); // 24
console.log(permutations([]));                          // [ [] ]
console.log(permutations([1, 1]));                      // [ [ 1, 1 ], [ 1, 1 ] ]

24 results, and turning each into text and putting them in a Set, which keeps only unique values, still gives 24. So none repeat.

With repeated input values, though, you get repeated arrangements. [1, 1] gives two orderings that look the same, because the function swaps positions, not values.

Step 6: why this doesn't scale

Step 6

const factorial = (n) => (n <= 1 ? 1 : n * factorial(n - 1));
console.log(factorial(10)); // 3628800
console.log(factorial(12)); // 479001600

Ten values have over 3.6 million orderings. Twelve have 479 million. At that size you can't even hold the list in memory, let alone build it. Real problems that sound like "try every order" need a smarter approach, such as skipping orders that can't possibly win.

The full solution

The panel prints all six permutations of [1, 2, 3], checks the count for four values against 4!, and shows the empty list, the repeated values and the factorial growth. Press Run.

The answer

function permutations(xs) {
  if (xs.length <= 1) return [xs.slice()];
  return xs.flatMap((v, i) => {
    const rest = [...xs.slice(0, i), ...xs.slice(i + 1)];   // everything except v
    return permutations(rest).map((tail) => [v, ...tail]);
  });
}

const factorial = (n) => (n <= 1 ? 1 : n * factorial(n - 1));

const three = permutations([1, 2, 3]);
const four = permutations([1, 2, 3, 4]);

console.log('permutations of [1,2,3]:');
for (const p of three) console.log('  ', p.join(''));
console.log('count for 4 values:', four.length, ' 4! =', factorial(4));
console.log('all distinct      :', new Set(four.map((p) => p.join(','))).size);
console.log('empty input       :', permutations([]), '<- one ordering, the empty one');
console.log('duplicates        :', permutations([1, 1]), '<- two orderings that look the same');
console.log('10! =', factorial(10), ' 12! =', factorial(12), '<- why this does not scale');

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.

9 checks

test('all six orderings of three values', three, [[1, 2, 3], [1, 3, 2], [2, 1, 3], [2, 3, 1], [3, 1, 2], [3, 2, 1]]);
test('the count is n factorial', [four.length, factorial(4)], [24, 24]);
test('one element has a single ordering', permutations([1]), [[1]]);
test('and the empty list has one too', permutations([]), [[]]);
test('every permutation has the input length', four.every((p) => p.length === 4), true);
test('and no two of them are the same', new Set(four.map((p) => p.join(','))).size, 24);
test('the first result is the input order', permutations([3, 1, 2])[0], [3, 1, 2]);
test('duplicate inputs give duplicate orderings', [permutations([1, 1]).length, new Set(permutations([1, 1]).map(String)).size], [2, 1]);
test('12 values would be 479 million orderings', factorial(12), 479001600);

The recursion is the definition read aloud: every permutation is some element followed by a permutation of the rest. flatMap is what makes it one expression, since each choice of first element yields a whole batch of results.

permutations([]) returning [[]] rather than [] is the correct base case and the one people get wrong. There is exactly one way to arrange nothing, and returning an empty list instead makes every recursive call above it produce nothing at all.

The last assertion is the practical point. Factorial growth means 10 values is 3.6 million orderings and 12 is 479 million: at that size you cannot hold the answer, let alone build it. Any real problem phrased as "try every order" needs pruning, a heuristic, or a different formulation.

Common mistakes

  • Returning [] for the empty list. Every call above it then returns nothing. The empty list has one arrangement, so return [[]].
  • Using map instead of flatMap. The results end up nested one level too deep.
  • Removing the chosen item with splice on the input. That changes the caller's array and the list you are still looping over. Build rest from slices.

Try it yourself

  1. Use permutations to list every ordering of the letters in 'abc' as strings.
  2. Remove the repeats from permutations([1, 1, 2]) so only three orderings remain.
  3. Write countPermutations(n) that returns the count without building the list.

Keep practising

Newsletter

New writing, when it lands.

Occasional notes on shipping software with AI agents. No schedule, no filler, unsubscribe in one click.