Combine 2 arrays into a multidimensional array?

javascript

Solution

var array1 = ["Pepsi", "Coke", "Juice", "Water"],
    array2 = ["35", "17", "21", "99"],
    result = [], i = -1;

while ( array1[++i] ) { 
  result.push( [ array1[i], array2[i] ] );
}

As written, this solution assumes you will only ever be using strings. As @ajax333221 has pointed out in the comments below, this would cause problems if you were to involve `boolean` or `int` values into this solution. As such, I'd like to propose an improvement that will accomplish your goals, while not tripping over difficult values and types:

var array1 = [false, 0, "Juice", -1],
    array2 = ["35", "17", "21", "99"],
    result = [];

for ( var i = 0; i < array1.length; i++ ) {
  result.push( [ array1[i], array2[i] ] );
}

Problem

This is based on my last question. I have these arrays: ``` var array1 = new Array ("Pepsi", "Coke", "Juice", "Water"); var array2 = new Array ("35", "17", "21", "99"); ``` And I want to combine them to form a multidimensional array like this: ``` [ ["Pepsi","35"] ["Coke", "17"] ["Juice","21"] ["Water","99"] ] ``` I tried this script: ``` Values=[]; for (i = 0; i < array1.length; i++) { Values[i] = Array(array1[i], array2[i]); } ``` But it gave a result like this (correct values, incorrect names): ``` [ ["a","35"] ["c","17"] ["E","21"] ["I","99"] ] ```

Original source