如何生成多个数组的完全组合?
const source = [ ["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"] ];
const result = combination(source);
需要结果,就像笛卡尔积,但具有各种大小的组合:
["a"]
["a", "d"]
["a", "d", "g"]
...
["b"]
...
["b", "f", "i"]
...
["i"]
答案 0 :(得分:1)
如何?
function cartesianProduct(arrArr) {
if (arrArr.length === 0) return [];
const [firstArr, ...restArrs] = arrArr;
const partialProducts = cartesianProduct(restArrs || []);
let ret = firstArr.map(elem => [elem]);
ret = ret.concat(partialProducts);
ret = ret.concat(partialProducts.reduce((acc, product) => {
return acc.concat(firstArr.map(elem => [elem].concat(product)));
}, []));
return ret;
}