Files
30-seconds-of-code/snippets/cartesianProduct.md
Isabelle Viktoria Maciohsek 2ddddfe794 Update cartesianProduct.md
2020-12-29 12:31:43 +02:00

454 B

title, tags
title tags
cartesianProduct math,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.
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]]