gpt4 book ai didi

javascript - 检查两个数组中属性的相同值的快速方法?

转载 作者:行者123 更新时间:2023-11-28 14:15:49 26 4
gpt4 key购买 nike

我必须找到一种方法来检查两个数组中属性的相同值。

这里有两个包含对象的数组。

// carArray1

[
{ id: 1, driver: "Mario", carName: "Ferrari 488" },
{ id: 2, driver: "Solid Snake", carName: "Prious" },
{ id: 3, driver: "Link", carName: "Explorer" },
{ id: 4, driver: "Zelda", carName: "Genesis" },
{ id: 5, driver: "Ryu", carName: "Range Rover" }
]

// carArray2

[
{ id: 6, driver: "Chun-Li", carName: "Lamborghini" },
{ id: 7, driver: "Blanca", carName: "Camry" },
{ id: 3, driver: "Link", carName: "Explorer" },
{ id: 9, driver: "Kurby", carName: "Ferrari 911" },
{ id: 1, driver: "Mario", carName: "Ferrari 488" },
]

如您所见,carArray1carArray2 都包含相同的对象 ID 1 和 3。

我正在考虑使用map方法迭代carArray2数组

carArray1.map(car1 => 
carArray2.map(car2 =>
car1.id === car2.id ? console.log("same property!") : '')
)

我可以期待“相同的属性(property)!”在控制台中显示两次消息,但我想在不使用双循环的情况下实现它。

最佳答案

要快速完成此操作(O(n) 时间),首先迭代其中一个数组并将 id 放入 Set 中,然后迭代第二个数组并检查该数组的 ID 是否为当前对象在集合中:

const arr1 = [
{ id: 1, driver: "Mario", carName: "Ferrari 488" },
{ id: 2, driver: "Solid Snake", carName: "Prious" },
{ id: 3, driver: "Link", carName: "Explorer" },
{ id: 4, driver: "Zelda", carName: "Genesis" },
{ id: 5, driver: "Ryu", carName: "Range Rover" }
];

const arr2 = [
{ id: 6, driver: "Chun-Li", carName: "Lamborghini" },
{ id: 7, driver: "Blanca", carName: "Camry" },
{ id: 3, driver: "Link", carName: "Explorer" },
{ id: 9, driver: "Kurby", carName: "Ferrari 911" },
{ id: 1, driver: "Mario", carName: "Ferrari 488" },
];

const arr1Ids = new Set(arr1.map(({ id }) => id));
arr2.forEach(({ id }) => {
if (arr1Ids.has(id)) {
console.log('duplicate id:', id);
}
});

关于javascript - 检查两个数组中属性的相同值的快速方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57506924/

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