arvitaly
arvitaly

Reputation: 161

Generating full (all sizes) combinations of arrays

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

Answers (1)

ack_inc
ack_inc

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

Related Questions