gpt4 book ai didi

Javascript:从 2 个数组中查找不匹配的对象

转载 作者:搜寻专家 更新时间:2023-11-01 04:59:14 26 4
gpt4 key购买 nike

我有 2 个对象数组

var arr1 = [{id: "145", firstname: "dave", lastname: "jones"},
{id: "135", firstname: "mike",lastname: "williams"},
{id: "148", firstname: "bob",lastname: "michaels"}];
var arr2 = [{id: "146", firstname: "dave", lastname: "jones"},
{id: "135", firstname: "mike", lastname: "williams"},
{id: "148", firstname: "bob", lastname: "michaels"}];

我想找到其中一个数组中仅存在 id 的对象,然后将对象记录到控制台或将对象推送到新数组。

所以我想结束

var arr1 = [{id: "145", firstname: "dave", lastname: "jones"}]
var arr2 = [{id: "146", firstname: "dave", lastname: "jones"}]

我尝试使用 forEach 循环并将匹配的 id 从数组中拼接出来

arr1.forEach(function(element1, index1) {
let arr1Id = element1.id;
arr2.forEach(function(element2, index2) {
if (arr1Id === element2.id) {
arr1.splice(element1, index1)
arr2.splice(element2, index2)

};
});
});


console.log(arr1);
console.log(arr2);

但我最终得到了

arr1

[ { id: '135', firstname: 'mike', lastname: 'williams' },
{ id: '148', firstname: 'bob', lastname: 'michaels' } ]

arr2

 [ { id: '135', firstname: 'mike', lastname: 'williams' },
{ id: '148', firstname: 'bob', lastname: 'michaels' } ]

最佳答案

你可以拿一个Set对于每个数组的 id 并通过检查是否存在来过滤另一个数组。

var array1 = [{ id: "145", firstname: "dave", lastname: "jones" }, { id: "135", firstname: "mike", lastname: "williams" }, { id: "148", firstname: "bob", lastname: "michaels" }],
array2 = [{ id: "146", firstname: "dave", lastname: "jones" }, { id: "135", firstname: "mike", lastname: "williams" }, { id: "148", firstname: "bob", lastname: "michaels" }],
set1 = new Set(array1.map(({ id }) => id)),
set2 = new Set(array2.map(({ id }) => id)),
result1 = array1.filter(({ id }) => !set2.has(id)),
result2 = array2.filter(({ id }) => !set1.has(id));

console.log(result1);
console.log(result2);
.as-console-wrapper { max-height: 100% !important; top: 0; }

关于Javascript:从 2 个数组中查找不匹配的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55878764/

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