Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Combine same-index objects of two arrays

Say I have two arrays of objects, like so:

var arr1 = [{name: 'Jay'}, {name: 'Bob'}];
var arr2 = [{age: 22}, {age: 30}];

I want a combined array like so:

var arr3 = [{name: 'jay', age: 22}, {name: 'Bob', age: 30}];

You can safely assume that the two initial arrays will have indexes matching each other, meaning index 0 of arr1 will always go with index 0 of arr2.

What would be the fastest way to accomplish this? I was imagining a forEach loop nested inside another forEach loop and extending each object from arr1 with the current object from arr2, but I feel this may be too complex.

like image 510
la1ch3 Avatar asked Jan 07 '23 01:01

la1ch3


2 Answers

You can just iterate one array and create a new array using the index from the first iteration. There are many ways to do this. Here's one:

    var arr1 = [{name: 'Jay'}, {name: 'Bob'}];
    var arr2 = [{age: 22}, {age: 30}];

    var combined = arr1.map(function(item, index) {
        return {name: item.name, age: arr2[index].age};
    });
    document.write(JSON.stringify(combined));

If you really want the maximum performance, you'd have to test a number of schemes in a number of different browsers. For example, sometimes a for loop is faster than the built-in array methods in some browsers.

var arr1 = [{name: 'Jay'}, {name: 'Bob'}];
var arr2 = [{age: 22}, {age: 30}];
var combined = [];

for (var i = 0; i < arr1.length; i++) {
  combined[i] = {name: arr1[i].name, age: arr2[i].age};
}

document.write(JSON.stringify(combined));

FYI, the for loop option (the second option) looks quite a bit faster in all three browsers here in a jsperf.

enter image description here

like image 112
jfriend00 Avatar answered Jan 09 '23 20:01

jfriend00


In a for loop:

var arr1 = [{name: 'Jay'}, {name: 'Bob'}];
var arr2 = [{age: 22}, {age: 30}];


for(var i in arr1)
{
  arr1[i]['age'] = arr2[i]['age'];
}

console.log(arr1) //[Object { name="Jay",  age=22}, Object { name="Bob",  age=30}]

Now you have the merged result in arr1.

like image 21
Jorge Zuverza Avatar answered Jan 09 '23 18:01

Jorge Zuverza