Search code examples
javascriptarraysfunctioncombinations

How can I create every combination possible for the contents of two arrays?


I have two arrays:

var array1 = ["A", "B", "C"];
var array2 = ["1", "2", "3"];

How can I set another array to contain every combination of the above, so that:

var combos = ["A1", "A2", "A3", "B1", "B2", "B3", "C1", "C2", "C3"];

Solution

  • A loop of this form

    combos = [] //or combos = new Array(2);
    
    for(var i = 0; i < array1.length; i++)
    {
         for(var j = 0; j < array2.length; j++)
         {
            //you would access the element of the array as array1[i] and array2[j]
            //create and array with as many elements as the number of arrays you are to combine
            //add them in
            //you could have as many dimensions as you need
            combos.push(array1[i] + array2[j])
         }
    }