使用Javascript中的Set删除重复项

ess*_*ara 5 javascript set duplicates

我正在努力做一些非常简单的事情.我有一个对象数组.我需要根据id属性从这个数组中删除重复.所以我想创建一个Set包含我的ID,如下所示:

let myArray = [{
    id: 10,
    other: "bla"
  },
  {
    id: 15,
    other: "meh"
  },
  {
    id: 10,
    other: "bla"
  }
]

let indexes = new Set();
myArray.forEach(a => indexes.add(a.id));
console.log('indexes list', indexes)
Run Code Online (Sandbox Code Playgroud)

indexes总是空的.我究竟做错了什么?谢谢.

编辑:我选择@Hyyan Abo Fakher作为正确的答案,因为他是对的,但@bambam评论中的建议是解决整个问题的一个很好的解决方案.谢谢大家.

Nen*_*car 5

您可以使用filterwith方法通过Set创建新的唯一对象数组id

const data = [{id: 10, other: "bla"},{id: 15, other: "meh"},{id: 10, other: "bla"}]

let result = data.filter(function({id}) {
  return !this.has(id) && this.add(id);
}, new Set)

console.log(result)
Run Code Online (Sandbox Code Playgroud)


Hyy*_*her 2

但索引总是空的。我究竟做错了什么?

您的代码完全正常工作,问题似乎来自浏览器控制台本身,您期望打印到set控制台将打印数组中的项目,但实际上,浏览器只会打印对象实例

在 StackOverflow 上运行代码将打印indexes list {},但实际上,浏览器控制台打印了其他内容。

在此输入图像描述

要确保列表不为空,请使用该size属性

let myArray = [{
    id: 10,
    other: "bla"
  },
  {
    id: 15,
    other: "meh"
  },
  {
    id: 10,
    other: "bla"
  }
]

let indexes = new Set();
myArray.forEach(a => indexes.add(a.id));
console.log('indexes list', indexes.size)
Run Code Online (Sandbox Code Playgroud)

要循环您需要使用的集合for ... of

let myArray = [{
    id: 10,
    other: "bla"
  },
  {
    id: 15,
    other: "meh"
  },
  {
    id: 10,
    other: "bla"
  }
]

let indexes = new Set();
myArray.forEach(a => indexes.add(a.id));
for (let item of indexes) console.log(item);
Run Code Online (Sandbox Code Playgroud)