Merge 2 arrays into a multidimensional array?

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 as follows:

 [ ["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 he gave this result (correct values, wrong names):

 [ ["a","35"] ["c","17"] ["E","21"] ["I","99"] ] 
+4
source share
2 answers
 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 that you will only use strings. As @ ajax333221 noted in the comments below, this will cause problems if you include boolean or int values ​​in this solution. Thus, I would like to suggest an improvement that will achieve your goals without disabling complex 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] ] ); } 
+15
source

You can use .map() in an array.

 var Values = array1.map(function(v,i) { return [v, array2[i]]; }); 

See the MDN slot for older browsers.

live demo: http://jsfiddle.net/D9rjf/


If you are going to perform this operation quite a bit, you can make a reusable function.

In this example, I extended Array.prototype , but this is not necessary if you do not like it.

 Array.prototype.combine = function(arr) { return this.map(function(v,i) { return [v, arr[i]]; }); }; 

 var Values = array1.combine(array2); 

live demo: http://jsfiddle.net/D9rjf/1/

+5
source

Source: https://habr.com/ru/post/1412836/


All Articles