简体   繁体   中英

Merge/replace Javascript arrays

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]]

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 ] ]

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 ] ]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM