30秒学会 JavaScript 片段 · 2023年9月22日

30秒学会 JavaScript 片段 – Cartesian product

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]]

翻译自:https://www.30secondsofcode.org/js/s/cartesian-product