30秒学会 JavaScript 片段 · 2022年5月11日

30秒学会 JavaScript 片段 – Cross product of arrays

Creates a new array out of the two supplied by creating each possible pair from the arrays.

  • Use Array.prototype.reduce(), Array.prototype.map() and Array.prototype.concat() to produce every possible pair from the elements of the two arrays.

代码实现

const xProd = (a, b) =>
  a.reduce((acc, x) => acc.concat(b.map(y => [x, y])), []);

xProd([1, 2], ['a', 'b']); // [[1, 'a'], [1, 'b'], [2, 'a'], [2, 'b']]

翻译自:https://www.30secondsofcode.org/js/s/cross-product-of-arrays