Add cartesianProduct
This commit is contained in:
committed by
Chalarangelo
parent
33f3c8c83c
commit
dfd3ebd398
18
snippets/cartesianProduct.md
Normal file
18
snippets/cartesianProduct.md
Normal file
@ -0,0 +1,18 @@
|
||||
---
|
||||
title: cartesianProduct
|
||||
tags: array,beginner
|
||||
---
|
||||
|
||||
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]]
|
||||
```
|
||||
Reference in New Issue
Block a user