gpt4 book ai didi

javascript - 比较 2 个对象数组并删除重复项

转载 作者:数据小太阳 更新时间:2023-10-29 05:09:07 32 4
gpt4 key购买 nike

我在 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;
}

最佳答案

O(N) 复杂度的一个选项是在 cars1 中制作 Setid >,然后将 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);

同时排序:

combined.sort(({ id: aId }, {id: bId }) => aId - bId);

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);

关于javascript - 比较 2 个对象数组并删除重复项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54142112/

32 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com