Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
10
rated 0 times [  17] [ 7]  / answers: 1 / hits: 112657  / 11 Years ago, sun, october 20, 2013, 12:00:00

What's the correct way to merge two arrays in Javascript?



I've got two arrays (for example):



var a1 = [{ id : 1, name : test}, { id : 2, name : test2}]
var a2 = [{ id : 1, count : 1}, {id : 2, count : 2}]


I want to be able to end up with something like:



var a3 = [{ id : 1, name : test, count : 1}, 
{ id : 2, name : test2, count : 2}]


Where the two arrays are being joined based on the 'id' field and extra data is simply being added.



I tried to use _.union to do this, but it simply overwrites the values from the second array into the first one


More From » arrays

 Answers
42

This should do the trick:


var mergedList = _.map(a1, function(item){
return _.extend(item, _.findWhere(a2, { id: item.id }));
});

This assumes that the id of the second object in a1 should be 2 rather than "2"


[#74856] Friday, October 18, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
kadinl

Total Points: 321
Total Questions: 117
Total Answers: 103

Location: Nepal
Member since Mon, Jan 4, 2021
3 Years ago
;