-2

I have an array in this form ...

  • arr[itemDescription]
    • [0] someValue1
    • [1] someotherValue1
  • arr[itemDescription]
    • [0] someValue2
    • [1] someotherValue2
  • arr[itemDescription]
    • [0] someValue3
    • [1] someotherValue3
  • ....

Now i would like to generate all possible variations where i have an array with the first item combined with the other elements, the second element combined with the other elements and so on. Like:

  • [someValue1][someValue2][someValue3]
  • [someValue1][someotherValue2][someValue3]
  • [someValue1][someotherValue2][someotherValue3]
  • ....

to sum up, for the folowing input array:

[[11, 12], [21, 22], [31, 32]];

I need to obtain an output array like

[[11, 21, 31], [11, 21, 32], [11, 22, 31], [11, 22, 32], [12, 21, 31], [12, 21, 32], [12, 22, 31], [12, 22, 32]];

Can somebody help me how I would do that in javascript?

Thank you a lot!

Fez Vrasta
  • 14,110
  • 21
  • 98
  • 160

1 Answers1

0

I propose this solution. To decide to choose the index of sub array iside input array, I use array dimension modulo global index :

var input = [[11, 12], [21, 22], [31, 32]];
var dim = Math.pow(2, input.length);
var output = new Array(dim);
output.fill(0);
input.forEach((x,i) => {
  var limit = dim / Math.pow(2, i+1);
  output.forEach((y,j,arr) => {
    var index = Math.floor((j+1)/limit) % 2;
    if (i === 0)
      arr[j] = [x[index]];
    else
      arr[j].push(x[index]);
  });
});
console.log(output);
kevin ternet
  • 4,514
  • 2
  • 19
  • 27