首页 > 解决方案 > Angular - 使用集合从数组中删除重复对象

问题描述

我需要从我的数组中删除所有重复的对象。我知道我可以通过使用过滤器或减少来做到这一点,但我想使用 set 来代替,因为(如果它有效)它应该是最短和最干净的选项。

原始数组

[{type: "A", label: "A", department: "C"},
{type: "B", label: "B", department: "C"},
{type: "B", label: "B", department: "C"}]

预期输出:

[{type: "A", label: "A", department: "C"},
{type: "B", label: "B", department: "C"}]

我试过:

distinctArray = new Set(origionalArray);

但它返回原始数组。所以我的猜测是它通过引用比较对象。在java中我会覆盖equals方法。但是据我在网上可以找到,这不能在 TS 中完成。

有什么想法可以完成吗?感谢您的帮助和时间。

标签: arraystypescript

解决方案


您可以使用它从 TS 中的数组中删除重复项。

const expected = new Set();
const unique = arr.filter(item => !expected.has(JSON.stringify(item)) ? expected.add(JSON.stringify(item)) : false);

推荐阅读