I have 2 arrays of objects in JavaScript and would like to compare and merge the contents and sort the results by id. Specifically, the resulting sorted array should contain all objects from the 1st array, plus all objects from the 2nd array that have an id that's not in the 1st.
The following code seems to work (minus the sorting). But there must be a better, more succinct way to do this, particularly with features from ES6. I assume using a Set is the way to go, but not sure exactly how to implement.
var cars1 = [
{id: 2, make: "Honda", model: "Civic", year: 2001},
{id: 1, make: "Ford", model: "F150", year: 2002},
{id: 3, make: "Chevy", model: "Tahoe", year: 2003},
];
var cars2 = [
{id: 3, make: "Kia", model: "Optima", year: 2001},
{id: 4, make: "Nissan", model: "Sentra", year: 1982},
{id: 2, make: "Toyota", model: "Corolla", year: 1980},
];
// Resulting cars1 contains all cars from cars1 plus unique cars from cars2
cars1 = removeDuplicates(cars2);
console.log(cars1);
function removeDuplicates(cars2){
for (entry in cars2) {
var keep = true;
for (c in cars1) {
if (cars1[c].id === cars2[entry].id) {
keep = false;
}
}
if (keep) {
cars1.push({
id:cars2[entry].id,
make:cars2[entry].make,
model:cars2[entry].model,
year:cars2[entry].year
})
}
}
return cars1;
}