生成完整(所有大小)的数组组合

时间:2018-12-15 03:47:37

标签: javascript combinations cartesian-product

如何生成多个数组的完全组合?

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"]

1 个答案:

答案 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;
}