Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript array of arrays

I have the following arrays:

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

Once Populated, they will be the same length. What I need is an array that pair the same index values of the arrays. Like so:

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

e.g.

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 populated?

like image 963
user906568 Avatar asked Aug 29 '11 20:08

user906568


People also ask

Can you put an array inside an array JavaScript?

An array is an ordered collection of values: each value is called an element, and each element has a numeric position in the array, known as its index. JavaScript lets us create arrays inside array called Nested Arrays.

How do you join array of arrays?

To merge elements from one array to another, we must first iterate(loop) through all the array elements. In the loop, we will retrieve each element from an array and insert(using the array push() method) to another array. Now, we can call the merge() function and pass two arrays as the arguments for merging.

How do you double an array in JavaScript?

In Chrome devtools, var array = [1,2,3]; array = array. concat(array); returns [1, 2, 3, 1, 2, 3] .

What is multidimensional array in JavaScript?

A multidimensional array is an array that contains another array. For example, // multidimensional array const data = [[1, 2, 3], [1, 3, 4], [4, 5, 6]];


2 Answers

If you know they are always the same length, simply loop through one and add both to the result:

var data = [];

for(var i=0; i<dates.length; i++){
    data.push([dates[i], answers[i]]);
}
like image 150
James Montagne Avatar answered Sep 18 '22 16:09

James Montagne


var data = $.map(dates, function(v,i) { return [ [ v,answers[i] ] ]; });

You can use the jQuery.map()[docs] method, but you need to double-wrap the returned Array because when $.map gets an Array, it performs a concat.

like image 37
user113716 Avatar answered Sep 20 '22 16:09

user113716