# Cartesian product of two JavaScript arrays

The Cartesian product or cross product of two arrays is a new array that contains every possible pair of elements from the two arrays. This can be useful in many mathematical and programming scenarios.

In order to calculate the Cartesian product of two arrays, you can use `Array.prototype.reduce()` on the first array and `Array.prototype.map()` on the second array to create each possible pair. Then, you can use the spread operator (`...`) to concatenate the pairs into a single array.

```const crossProduct = (a, b) =>
a.reduce((acc, x) => [...acc, ...b.map(y => [x, y])], []);

crossProduct([1, 2], ['a', 'b']);
// [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]```

## More like this

• Collection · 108 snippets

### JavaScript Arrays

Master array manipulation in JavaScript with this ES6 snippet collection.

• JavaScript ·

### Calculate the powerset of a JavaScript array

Generate the powerset of a given array of numbers or other primitive values.

• JavaScript ·

### Midpoint of two points

Calculate the midpoint between two pairs of points in a 2D plane, and beyond.

• JavaScript ·

### Generate a JavaScript array of random integers in a given range

Combining `Math.random()` and a few simple math operations, you can generate an array of random integers in a specified range.

Start typing a keyphrase to see matching snippets.