更新于 2023-03-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 ] ]