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

问题描述 投票:3回答:2

有两个数组:

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

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

最终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;
});
javascript arrays filter hash
2个回答
2
投票

如果属性顺序是可预测的,请首先在arr2中设置一组字符串项,然后根据该集合中是否存在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);

0
投票

您应该比较那些对象中的ID,而不是对象引用。

const idsInArr2 = arr2.map(val => val.id);
arr1 = arr1.filter(val => idsInArr2.indexOf(val.id) === -1);
© www.soinside.com 2019 - 2024. All rights reserved.