arrays - 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 中完成。
有什么想法可以完成吗?感谢您的帮助和时间。
解决方案
您可以使用它从 TS 中的数组中删除重复项。
const expected = new Set();
const unique = arr.filter(item => !expected.has(JSON.stringify(item)) ? expected.add(JSON.stringify(item)) : false);
推荐阅读
- matplotlib - 如何更改 matplotlib“配置子图”窗口的图标?
- kotlin - 为什么 Kotlin double equals 找不到 .equals 方法?
- vue.js - 在搜索中输入时阻止提交表单数据
- java - \s 实际上并没有捕获所有空白字符
- webpack - Webpack'ing "sass" (dart-sass),使用需要动态、硬代码依赖到上下文?
- java - 单选按钮在滚动时搞砸了
- jsf - 验证错误后视图更新不正确
- html - 用网页上的 vba 按下表格内的链接
- angular - 角度测试并在 e2e 中出错
- node.js - 使用 node.js 进行 Soap Web 服务监控、遥测和指标