Reputation: 161
How to generate fully combinations of multiple arrays?
const source = [ ["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"] ];
const result = combination(source);
Need result, like a cartesian product, but with combinations of all sizes:
["a"]
["a", "d"]
["a", "d", "g"]
...
["b"]
...
["b", "f", "i"]
...
["i"]
Upvotes: 0
Views: 55
Reputation: 1103
How about this:
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;
}
Upvotes: 1