JavaScript
Array Permutations
Programming
Web Development
Coding Tutorial

Find all permutations of 2 arrays in JS

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Questions about “permutations of two arrays” usually mean one of two very different things. Sometimes the goal is to pair every value from the first array with every value from the second array, which is a Cartesian product. Other times the goal is to merge the arrays and generate every possible ordering, which is a true permutation problem. The correct JavaScript solution depends entirely on which output you actually want.

Case One: Every Pair Between the Two Arrays

If you want every combination formed by taking one item from the first array and one item from the second, use a Cartesian product.

javascript
1const left = [1, 2];
2const right = ["x", "y"];
3
4const pairs = [];
5
6for (const a of left) {
7  for (const b of right) {
8    pairs.push([a, b]);
9  }
10}
11
12console.log(pairs);

Output:

text
[ [ 1, 'x' ], [ 1, 'y' ], [ 2, 'x' ], [ 2, 'y' ] ]

This is not a permutation in the strict mathematical sense. It is the Cartesian product of the two input arrays.

A More Compact JavaScript Version

If you prefer a functional style, flatMap expresses the same idea cleanly:

javascript
1const left = [1, 2];
2const right = ["x", "y"];
3
4const pairs = left.flatMap(a => right.map(b => [a, b]));
5console.log(pairs);

This is a good default for ordinary application code because it stays concise without becoming obscure.

Case Two: True Permutations of the Combined Values

If you really mean “combine both arrays and list every possible ordering,” then you need a permutation algorithm.

javascript
1function permute(items) {
2  if (items.length <= 1) {
3    return [items.slice()];
4  }
5
6  const result = [];
7
8  for (let i = 0; i < items.length; i += 1) {
9    const current = items[i];
10    const rest = items.slice(0, i).concat(items.slice(i + 1));
11
12    for (const tail of permute(rest)) {
13      result.push([current, ...tail]);
14    }
15  }
16
17  return result;
18}
19
20const merged = [1, 2, "x"];
21console.log(permute(merged));

This generates every ordering of the merged array. That is a true permutation problem, and the result set grows very quickly.

Why the Distinction Matters

The two problems have very different output sizes.

For arrays of lengths m and n:

  • the Cartesian product returns m * n pairs
  • permutations of the merged array return (m + n)! arrangements

That difference is enormous. If you choose the wrong interpretation, you can end up with code that is either far more expensive than necessary or simply produces the wrong shape of data.

This is why the first debugging question should always be: what should one result element look like?

If one result element looks like [leftValue, rightValue], you want a Cartesian product. If it looks like a full reordering of all items, you want permutations.

A Reusable Cartesian Product Helper

Here is a small helper when the pair-generation case is the real goal:

javascript
1function cartesianProduct(a, b) {
2  return a.flatMap(leftValue => b.map(rightValue => [leftValue, rightValue]));
3}
4
5console.log(cartesianProduct([1, 2], ["x", "y", "z"]));

This is usually what people mean when they say "all combinations from two arrays."

Watch for Duplicates and Large Inputs

If either array contains duplicate values, both algorithms will produce repeated-looking outputs unless you deduplicate first. That may or may not be correct depending on whether the duplicates are semantically different items.

Also pay attention to growth:

  • Cartesian products scale reasonably for moderate arrays
  • permutations become expensive very quickly because factorial growth explodes fast

For example, permuting even ten combined elements already produces millions of results. That is often a sign you need a different algorithm or a streaming approach.

When You Might Want Nested Products Instead

Some developers ask for “permutations of two arrays” when they really want combinations of more than two collections, such as one value from each of several arrays. That is still a Cartesian-product family problem, not a permutation problem.

The algorithm choice should follow the required shape of the output, not the label used in the original question.

Common Pitfalls

One common mistake is calling the Cartesian product a permutation. The terms are related only loosely in casual conversation, but they describe different algorithms.

Another mistake is writing a permutation function when the task only needs pairs. That makes the solution slower and harder to understand than necessary.

Developers also sometimes forget how quickly full permutations grow. A small-looking input can generate an impractically large result set.

Finally, be clear about duplicates. If equal values appear in the input arrays, the output may contain repeated-looking combinations or orderings unless you explicitly remove duplicates first.

Summary

  • If you want one value from each of two arrays, compute the Cartesian product.
  • If you want every ordering of all combined values, use a permutation algorithm.
  • In JavaScript, nested loops or flatMap are clean solutions for the Cartesian-product case.
  • True permutations grow factorially, so they become expensive very quickly.
  • Clarify the expected output shape before choosing the algorithm.

Course illustration
Course illustration

All Rights Reserved.