Reputation: 6242
I have two object arrays (which I receive from a server based on some user input):
array1 = [{id:1, name:Bob}, {id:2, name:John}, {id:3, name:Mary}];
array2 = [{id:2, field:true},{id:2, field:true}, {id:3, field:false}];
The id's in both array correspond to each other (they are user ids). In real life these arrays will be much larger (up to 8000 elements in array 1, and 16000 in array2).
The thing I need to accomplish is on the front end I am currently showing just array2 information which displays to the user id and the field. The problem is the front end user doesn't know anyone by their user id instead they know them by their name. I need an array which has objects which look like this: {id:'',name:'',field:''}
.
My first thought was to create a new array and "combine the two arrays" :
var new_array = [];
for (var i = 0; i < array2.length; i++) {
var name = 'Unknown';
for (var j = 0; j < array1.length; j++) {
if (array1[j].id === array2[i].id) {
name = array1[j].name;
}
this.new_array.push({
id: array2[i].id,
name: name,
field: array1[j].field
});
}
}
So I loop through the the second array and check if the id matches the id of the first array. If it does I take the name from the first array and that is the user's name so that is how I get the user's name.
This works, but it is kind of slow on the front end, it take a few seconds to do this and if there are many items the user experience doesn't feel good there is a lot of waiting. I am looking for a more efficient way to do what I need to do.
Upvotes: 4
Views: 3636
Reputation: 413702
Run through one array and create an object to map id values to entries:
var array2idx = array2.reduce(function(map, value) {
map[value.id] = value;
return map;
}, {});
Now you can find the array2
values with a simple lookup:
var new_array = [];
for (var i = 0; i < array1.length; i++) {
var v2 = array2idx[array1[i].id];
if (v2) {
new_array.push({
id: v2.id,
name: array1[i].name,
field: array1[i].field
});
}
}
That should be considerably faster. Looking up an id in the index object will take almost no time at all.
Upvotes: 4