更新于2023年3月31日 15:39:43
539 次浏览
我们需要编写一个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 ] ]