Array of javascript arrays

I have the following arrays:

var dates = new Array(); var answers = new Array(); 

After filling, they will have the same length. I need an array that combines the same array index values. For instance:

 var pairedArray = new Array(); //pairedArray should have the form: [[dates[0], answers[0]], [dates[1], answers[1]], ...., [dates[n-1], answers[n-1]]] 

eg.

 data: [ [Date.UTC(2010, 0, 1), 29.9], [Date.UTC(2010, 2, 1), 71.5], [Date.UTC(2010, 3, 1), 106.4] ] 

How is this possible, given that I have two arrays of the same length, answers and dates that are already filled?

+4
source share
4 answers

If you know that they always have the same length, just skip one of them and add both results:

 var data = []; for(var i=0; i<dates.length; i++){ data.push([dates[i], answers[i]]); } 
+4
source
 var data = $.map(dates, function(v,i) { return [ [ v,answers[i] ] ]; }); 

You can use the jQuery.map() [docs] method, but you need to wrap the returned array twice, because when $.map gets the array, it executes concat .

+2
source
 var firstArray = ... var secondArray = ... if (firstArray.length === secondArray.length) { var result = []; for (var i = 0; i < firstArray.length; i++) { result.push({ [ firstArray[i], secondArray[i] ] }); } // TODO: do something with the result } 
+1
source

try it

 var dates = new Array(); var answers = new Array(); var pairedArray = new Array(); $.each(dates, function(i){ pairedArray.push([ dates[i], answers[i] ]); }); 
0
source

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


All Articles