Skip to content
Advertisement

How do arrange arrays with different combinations?

I have 3 arrays ["s","m"], ["Red","Black"], ["1", "2"]. I want to arrange them like this:

["s","Red","1"],
["s","Red","2"], 
["s","Black","1"], 
["s","Black","2"],

["m","Red","1"],
["m","Red","2"], 
["m","Black","1"], 
["m","Black","2"],

I’m out of idea, please help me.

Advertisement

Answer

Loop each one then just combine them into an array.

Script:

function test() {
  arr1 = ["s","m"]
  arr2 = ["Red","Black"]
  arr3 = ["1", "2"]

  arr1.forEach(x => {
    arr2.forEach(y => {
      arr3.forEach(z => {
        console.log([x, y, z]);
      });
    });
  });
}

Output:

output

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement