How to compute the cartesian product of multiple arrays in JavaScript?

Sometimes, we want to compute the cartesian product of multiple arrays in JavaScript.

In this article, we’ll look at how to compute the cartesian product of multiple arrays in JavaScript.

How to compute the cartesian product of multiple arrays in JavaScript?

To compute the cartesian product of multiple arrays in JavaScript, we can use the array flatMap and reduce methods.

For instance, we write

const data = [
  [1, 2],
  [10, 20],
  [100, 200, 300],
];
const prod = data.reduce(
  (a, b) => a.flatMap((x) => b.map((y) => [...x, y])),
  [[]]
);

to call data.reduce with a callback that calls a.flatMap with a callback that calls b.map with a callback to spread the entries of x and y in a new array and returns it.

This will get the entries from each array and put them in the nested arrays will do this for all combinations of entries for all arrays.

Conclusion

To compute the cartesian product of multiple arrays in JavaScript, we can use the array flatMap and reduce methods.