Javascript: Merge Two Arrays of Objects, Only If Not Duplicate (Based on Specified Object Key)
You can create a set of IDs from initialData
and this will make "check if ID is already in initial data" faster - O(1):
var initialData = [{
'ID': 1,
'FirstName': 'Sally'
},
{
'ID': 2,
'FirstName': 'Jim'
},
{
'ID': 3,
'FirstName': 'Bob'
}
];
var newData = [{
'ID': 2,
'FirstName': 'Jim'
},
{
'ID': 4,
'FirstName': 'Tom'
},
{
'ID': 5,
'FirstName': 'George'
}
];
var ids = new Set(initialData.map(d => d.ID));
var merged = [...initialData, ...newData.filter(d => !ids.has(d.ID))];
console.log(merged);
The final runtime of this approach is O(n + m).
If you want to be slightly more efficient, you can consider looping through newData
and pushing any new elements to the final result array manually (instead of using filter
and the spread operator).