gpt4 book ai didi

javascript - 从js中的两个数组中删除重复的哈希?

转载 作者:行者123 更新时间:2023-12-01 16:18:25 25 4
gpt4 key购买 nike

有两个数组:

arr1 = [
{name: "gunner", id: 639, label: "group"},
{name: "Gunners", id: 1313, label: "channel", isPrivate: false}
]
arr2 = [
{name: "gunner", id: 639, label: "group"}
]

需要删除 arr1 中存在于 arr2 中的所有值?

最终 arr1 将是,因为 arr2 已经有 {name: "gunner", id: 639, label: "group"}:

arr1 = [
{name: "Gunners", id: 1313, label: "channel", isPrivate: false}
]

我试过了,但没有按预期工作。

arr1 = arr1.filter(function(val) {
return arr2.indexOf(val) == -1;
});

最佳答案

如果属性顺序是可预测的,首先将 arr2 中的字符串化项目组成一个 Set,然后根据 arr1 中的字符串化项目是否存在于该集合中进行过滤:

const arr1 = [
{name: "gunner", id: 639, label: "group"},
{name: "Gunners", id: 1313, label: "channel", isPrivate: false}
];
const arr2 = [
{name: "gunner", id: 639, label: "group"}
];
const arr2Set = new Set(arr2.map(JSON.stringify));

const output = arr1.filter(obj => !arr2Set.has(JSON.stringify(obj)));
console.log(output);

如果您不想或不能进行字符串化,则改为遍历对象的每个 Object.entries,并检查是否不是每个条目都与另一个数组匹配:

const arr1 = [
{name: "gunner", id: 639, label: "group"},
{name: "Gunners", id: 1313, label: "channel", isPrivate: false}
];
const arr2 = [
{name: "gunner", id: 639, label: "group"}
];

const output = arr1.filter((obj1) => {
const entries1 = Object.entries(obj1);
return arr2.every(obj2 => (
entries1.length !== Object.keys(obj2).length ||
entries1.some(([key, val]) => obj2[key] !== val)
));
});

console.log(output);

关于javascript - 从js中的两个数组中删除重复的哈希?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59526189/

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