javascript 列表的笛卡尔积

javascript cartesian product of lists

我需要两个 javascript 列表的笛卡尔积。

示例:

let l1 = ['a','e','f'];
let l2 = ['1','3','2'];
let lp = prod(l1, l2);

lp 会是

[
['a','1'],
['e','1'],
['f','1'],
['a','3'],
['e','3'],
['f','3'],
['a','2'],
['e','2'],
['f','2']
]

我可以使用 for/foreach 循环轻松完成,但想知道是否有人会对地图函数提出优雅的建议。

尝试如下

let l1 = ['a','e','f'];
let l2 = ['1','3','2'];

console.log(l1.map(a => {
  return l2.map(b => {
    return [a,b];
  })
}).flat())

您可以结合使用 reduce 和 map:

console.log(l1.reduce((result, el1) => {
  result.push(...l2.map((el2) => [el1, el2]));
  return result;
}, []));

这应该有效:

function prod(l1, l2) {
  return l2.reduce(
    (p, b) => p.concat(l1.map(a => [a, b])),
    [],
  );
}

const l1 = ['a','e','f'];
const l2 = ['1','3','2'];
const lp = prod(l1, l2);

console.log(lp);

您可以通过减少数组并构建新数组来采用适用于两个以上数组的方法。

let l1 = ['a','e','f'],
    l2 = ['1','3','2'],
    result = [l1, l2]
        .reduce((a, b) => a.reduce((r, v) => r.concat(b.map(w => [].concat(v, w))), []));

console.log(result);
.as-console-wrapper { max-height: 100% !important; top: 0; }