-1

I want to print all possible combinations of each of the numbers in the array and store all of the combinations inside an array.

So far what I have only flattens the array.

I know I need a function that takes an array as an argument and then returns all possible combinations.

let array = [
  [0, 1, 8],
  [2, 3],
  [4, 5]
 ];

const allPossibleCombinations = function (array) {
  const combinations = [];
        return array.reduce((p,c) =>
          [...p, ...c] );
};

console.log(allPossibleCombinations(array))

But I need this result

[ '0 2 4',
  '0 2 5',
  '0 3 4',
  '0 3 5',
  '1 2 4',
  '1 2 5',
  '1 3 4',
  '1 3 5',
  '8 2 4',
  '8 2 5',
  '8 3 4',
  '8 3 5' ]
gab
  • 1
  • 2

1 Answers1

0

Probably not the most efficient solution, but this produces the desired output:

const [one, two, three] = [
  [0, 1, 8],
  [2, 3],
  [4, 5]
];
const output = [];

for (let i of one) {
   for (let j of two) {
      for (let h of three) {
         output.push([i, j, h]);
      }
   }
}

console.log(output);
Rob M.
  • 35,491
  • 6
  • 51
  • 50