4

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?

asked Aug 29, 2011 at 20:04
2
  • 1
    i wouldn't do the inside as an array. Commented Aug 29, 2011 at 20:07
  • Just a minor nitpick - in general, [] notation is way more awesome than new Array() Commented Aug 29, 2011 at 20:33

4 Answers 4

4

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]]);
}
answered Aug 29, 2011 at 20:06
Sign up to request clarification or add additional context in comments.

Comments

2
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.

answered Aug 29, 2011 at 20:14

Comments

1
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
}
answered Aug 29, 2011 at 20:06

1 Comment

Don't think that will work with the {} unless you give the property a name {something: [...]}
0

Try this

var dates = new Array();
var answers = new Array();
var pairedArray = new Array();
$.each(dates, function(i){
 pairedArray.push([ dates[i], answers[i] ]);
});
answered Aug 29, 2011 at 20:08

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.