我们需要编写一个包含多个数字数组的JavaScript函数。该函数应返回所有数组中元素的笛卡尔积的数组。
例如-
如果输入数组是-
[1, 2], [10, 20], [100, 200, 300]
那么输出应该是-
const output = [ [ 1, 10, 100 ], [ 1, 10, 200 ], [ 1, 10, 300 ], [ 1, 20, 100 ], [ 1, 20, 200 ], [ 1, 20, 300 ], [ 2, 10, 100 ], [ 2, 10, 200 ], [ 2, 10, 300 ], [ 2, 20, 100 ], [ 2, 20, 200 ], [ 2, 20, 300 ] ];
const arr1 = [1, 2]; const arr2 = [10, 20]; const arr3 = [100, 200, 300]; const cartesianProduct = (...arr) => { return arr.reduce((acc,val) => { return acc.map(el => { return val.map(element => { return el.concat([element]); }); }).reduce((acc,val) => acc.concat(val) ,[]); }, [[]]); }; console.log(cartesianProduct(arr1, arr2, arr3));
输出结果
这将产生以下输出-
[ [ 1, 10, 100 ], [ 1, 10, 200 ], [ 1, 10, 300 ], [ 1, 20, 100 ], [ 1, 20, 200 ], [ 1, 20, 300 ], [ 2, 10, 100 ], [ 2, 10, 200 ], [ 2, 10, 300 ], [ 2, 20, 100 ], [ 2, 20, 200 ], [ 2, 20, 300 ] ]