【发布时间】:2019-01-11 07:31:08
【问题描述】:
我在 JavaScript 中有 2 个对象数组,想比较和合并内容并按 id 对结果进行排序。具体来说,生成的排序数组应包含第一个数组中的所有对象,以及第二个数组中所有 id 不在第一个数组中的对象。
以下代码似乎有效(减去排序)。但是必须有更好、更简洁的方法来做到这一点,尤其是使用 ES6 的特性。我认为使用 Set 是可行的方法,但不确定如何实现。
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;
}
【问题讨论】:
-
这个问题应该发到Code Review | StackExchange
标签: javascript arrays ecmascript-6