hey*_*ush 3 javascript algorithm ecmascript-6
我有以下输入
input = [{a:[1,2]}, {b:[3,4]}];
Run Code Online (Sandbox Code Playgroud)
我想使用此输入来制作叉积输出
output = [{a:1, b:3},{a:1, b:4},{a:2, b:3},{a:2, b:4}];
Run Code Online (Sandbox Code Playgroud)
输入可以像
input = [{a:[1]}, {b:[2,4]}, {c:[3,5,6]}];
Run Code Online (Sandbox Code Playgroud)
可以使用Lodash或任何标准库。
您可以使用迭代和递归的方法。
function cartesian(array) {
function c(part, index) {
var k = Object.keys(array[index])[0];
array[index][k].forEach(function (a) {
var p = Object.assign({}, part, { [k]: a });
if (index + 1 === array.length) {
r.push(p);
return;
}
c(p, index + 1);
});
}
var r = [];
c({}, 0);
return r;
}
console.log(cartesian([{ a: [1, 2] }, { b: [3, 4] }]));
console.log(cartesian([{ a: [1] }, { b: [2, 4] }, { c: [3, 5, 6] }]));
Run Code Online (Sandbox Code Playgroud)
.as-console-wrapper { max-height: 100% !important; top: 0; }
Run Code Online (Sandbox Code Playgroud)