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

时间:2019-12-30 05:41:06

标签: javascript arrays filter hash

有两个数组:

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

4 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

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

const idsInArr2 = arr2.map(val => val.id);
arr1 = arr1.filter(val => idsInArr2.indexOf(val.id) === -1);

答案 2 :(得分:0)

您可以使用JSON.stringify比较循环中的对象:

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

var arr2 = [
  {name: "gunner", id: 639, label: "group"}
];

arr1 = arr1.filter(x => {
  for (var y of arr2) {
    if (JSON.stringify(x) !== JSON.stringify(y)) {
      return y;
    }
  }
});

console.log(arr1);

答案 3 :(得分:0)

尝试一下:

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 arr3 = arr1.filter(function(objArr1) {
  return arr2.findIndex(objArr2=>objArr2.id===objArr1.id) === -1;
});