1

I have an array of pairs like this (where the first item in each pair is just a basic index):

a1 = [[0, 3910], [1, 4910], [2, 19401]]

Then I have a second array of numbers:

a2 = [1384559999, 1371254399, 1360799999]

What I need to do is merge a1 and a2 so that items in a2 replace the first object in each parer from a1. Like so:

final = [[1384559999, 3910], [1371254399, 4910], [1360799999, 19401]]
2
  • 1
    You can just cycle through the arrays pretty simply. Are there more rules that make this complicated somehow? Commented Dec 18, 2013 at 0:55
  • Is the first value of each array supposed to be the index of that value in the second array? It makes a difference if so. Commented Dec 18, 2013 at 1:13

2 Answers 2

6

You can use Array.map to do this

a1 = [[0, 3910], [1, 4910], [2, 19401]]
a2 = [1384559999, 1371254399, 1360799999]

console.log(a2.map(function(current, index) {
    return [current, a1[index][1]]
}));

Output

[ [ 1384559999, 3910 ],
  [ 1371254399, 4910 ],
  [ 1360799999, 19401 ] ]
Sign up to request clarification or add additional context in comments.

Comments

0

Just because it's another solution...

This assumes that you meant that a1[i][0] is the index of the associated value in a2.

var a1 = [[0, 3910], [1, 4910], [2, 19401]];
var a2 = [1384559999, 1371254399, 1360799999];
var a3 = [];

for(var i = 0; i < a1.length; i++) {
    tmp = [a2[a1[i][0]], a1[i][1]]
    a3.push(tmp);
}

console.log(a3);

// [ [ 1384559999, 3910 ],
//   [ 1371254399, 4910 ],
//   [ 1360799999, 19401 ] ]

This still works if you change the value of the index, for example...

var a1 = [[2, 3910], [1, 4910], [0, 19401]];

// Should be... 
// [ [ 1360799999, 3910 ],
// [ 1371254399, 4910 ],
// [ 1384559999, 19401 ] ]

Here's what .map would look like if the first value in each pair in a1 are supposed to be the index of the value in a2.

var a1 = [[0, 3910], [1, 4910], [2, 19401]];
var a2 = [1384559999, 1371254399, 1360799999];

console.log(a1.map(function(current, index){
    return [ a2[current[0]], current[1] ];
}));

//[ [ 1384559999, 3910 ],
//  [ 1371254399, 4910 ],
//  [ 1360799999, 19401 ] ]

Comments

Your Answer

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.