generate combinations from 2d arrays duplicate

This has a lot of recursive characteristics, but it’s slightly more complicated than just permutations:

const foo = [
  ['a0', 'a1', 'a2'],
  ['b0', 'b1'],
  ['c0', 'c1'],
];

function getCombinations(prefixArr, arr) {
  if (!arr[0]) return prefixArr;

  return arr[0].map((element) => getCombinations(
    [...prefixArr, element],
    [...arr].splice(1),
  ));
}

function getCombinationsWrapper(arr) {
  let ans = getCombinations([], arr);
  for (let i = 0; i < arr.length - 1; i++) {
    ans = ans.flat();
  }
  return ans;
}

console.log(getCombinationsWrapper(foo));

CLICK HERE to find out more related problems solutions.

Leave a Comment

Your email address will not be published.

Scroll to Top