I try to do compare two array object and add new data to first array if id is match using below code but it is not working
first array sample :
first array
{
name :'sachin',
id :1
},
{
name :'dravid',
id :2
},
{
name :'ganguly',
id :3
}
second array sample
second array
{
score :186,
id :1
},
{
score :145,
id :2
},
{
score :183,
id :3
}
result array
result array :
{
name :'sachin',
highest :186,
id :1
},
{
name :'dravid',
highest :145,
id :2
},
{
name :'ganguly',
highest :183,
id :3
}
code i have tried to compare first and second array to check id is match.
let result = firstData.map(item => {
if (secondData && secondData.some(secondItem => secondItem.id === item.id)) {
return {
...item,
highest: secondItem.score
};
} else {
return {
...item,
highest: ''
};
}
});
console.log("result",result);
3
Answers
You are taking data from the second array incorrectly. You can do something like this:
You can use
reduce()
to build up a lookup object (or alternatively aMap
) which maps a user ID to a score and then usemap()
over the second array to use the user ID as a key to lookup the score for the user user currently iterating over. If the lookup is successful, return a new object with the propertyhighest
set to the lookup result. If not, just return a copy of the original object (of course you could also set a default value or whatever makes sense in your case).The solution will be
O(n)
in terms of time complexity.Alternatively instead of building up a lookup table you could also use
find()
and do a linear search in the array, which brings the overall time complexity toO(n²)
but in reality depending on how many elements you expect this might be faster. For general purposes the difference probably won’t matter much and if you need the performance measure, compare and then make a conscious decision.There are a lot of ways to do this. This is what I would do in my case:
Do try this and see how it goes.