I'm working with two arrays of objects in JavaScript and my goal is to compare, merge the contents, and sort by id. Specifically, I want the final sorted array to include all objects from the first array, as well as any objects from the second array that have an id not present in the first.
While the code provided below seems to achieve this (without sorting), I believe there must be a more concise way to accomplish this task, especially leveraging ES6 features. I suspect that using a Set might be the key, but I'm unsure about the implementation details.
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},
];
// The resulting cars1 should contain all cars from cars1 and 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;
}