Files
30-seconds-of-code/snippets/cartesian-product.md
Angelos Chalaris 61200d90c4 Kebab file names
2023-04-27 21:58:35 +03:00

533 B

title, tags, cover, firstSeen, lastUpdated
title tags cover firstSeen lastUpdated
Cartesian product math sail-away 2020-12-28T20:23:47+02:00 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.
const cartesianProduct = (a, b) =>
  a.reduce((p, x) => [...p, ...b.map(y => [x, y])], []);
cartesianProduct(['x', 'y'], [1, 2]);
// [['x', 1], ['x', 2], ['y', 1], ['y', 2]]