Files
30-seconds-of-code/snippets/cartesianProduct.md
Isabelle Viktoria Maciohsek 27c168ce55 Bake date into snippets
2021-06-13 13:55:00 +03:00

21 lines
530 B
Markdown

---
title: cartesianProduct
tags: math,array,beginner
firstSeen: 2020-12-28T20:23:47+02:00
lastUpdated: 2020-12-29T12:31:43+02:00
---
Calculates the cartesian product of two arrays.
- Use `Array.prototype.reduce()`, `Array.prototype.map()` and the spread operator (`...`) to generate all possible element pairs from the two arrays.
```js
const cartesianProduct = (a, b) =>
a.reduce((p, x) => [...p, ...b.map(y => [x, y])], []);
```
```js
cartesianProduct(['x', 'y'], [1, 2]);
// [['x', 1], ['x', 2], ['y', 1], ['y', 2]]
```