我在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;
}
Run Code Online (Sandbox Code Playgroud)
O(N)
复杂性的一个选择Set
是将id
s中的a cars1
,然后传播cars1
并过滤cars2
到输出数组中,过滤器测试id
在迭代中的汽车cars2
是否包含在集合中:
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},
];
const cars1IDs = new Set(cars1.map(({ id }) => id));
const combined = [
...cars1,
...cars2.filter(({ id }) => !cars1IDs.has(id))
];
console.log(combined);
Run Code Online (Sandbox Code Playgroud)
要sort
还有:
combined.sort(({ id: aId }, {id: bId }) => aId - bId);
Run Code Online (Sandbox Code Playgroud)
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},
];
const cars1IDs = new Set(cars1.map(({ id }) => id));
const combined = [
...cars1,
...cars2.filter(({ id }) => !cars1IDs.has(id))
];
combined.sort(({ id: aId }, {id: bId }) => aId - bId);
console.log(combined);
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1333 次 |
最近记录: |