Nest all content into snippets

This commit is contained in:
Angelos Chalaris
2023-05-07 16:07:29 +03:00
parent 2ecadbada9
commit 6a45d2ec07
1240 changed files with 0 additions and 0 deletions

View File

@ -0,0 +1,22 @@
---
title: Cartesian product
type: snippet
language: javascript
tags: [math]
cover: sail-away
dateModified: 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]]
```