javascript - 如何删除数组中具有相同值集的对象?
问题描述
给定以下对象数组,我将如何过滤掉
- 重复对象
- 具有相同属性集的对象(即我认为是重复
{ source: "A", target: "B", cost: 0 }
的{ source: "B", target: "A", cost: 3 }
......我不在乎保留哪个)
示例输入
let input = [
{ source: "A", target: "B", cost: 0 },
{ source: "A", target: "C", cost: 1 },
{ source: "A", target: "B", cost: 2 },
{ source: "B", target: "A", cost: 3 },
{ source: "D", target: "E", cost: 4 },
{ source: "E", target: "B", cost: 5 }
]
期望的输出
output = [
{ source: "A", target: "B", cost: 0 },
{ source: "A", target: "C", cost: 1 },
{ source: "D", target: "E", cost: 4 },
{ source: "E", target: "B", cost: 5 }
]
解决方案
结合 ( target
and source
) 和 ( source
and target
) 作为 one 的键Set
。
然后在其中一个Array.filter
检查当前项目是否存在于第一个中Set
,并将密钥添加到Set
.
let input = [
{ source: "A", target: "B", cost: 0 },
{ source: "A", target: "C", cost: 1 },
{ source: "A", target: "B", cost: 2 },
{ source: "B", target: "A", cost: 3 },
{ source: "D", target: "E", cost: 4 },
{ source: "E", target: "B", cost: 5 }
]
function filterout(src) {
let found = new Set()
return src.filter((item) => {
let result = found.has(`source:${item.source}, target:${item.target}`)
found.add(`source:${item.source}, target:${item.target}`)
found.add(`source:${item.target}, target:${item.source}`)
return !result
})
}
console.log(filterout(input))
推荐阅读
- r - 如何在组拆分产生的矩阵列表中重新绑定、排列和格式化数据
- azure-functions - 我可以在持久函数中传递或以某种方式获取由我的 orchestrationTrigger 函数中的 httpTrigger 函数生成的 orchestrationID 吗?
- javascript - 在对象中映射对象
- oauth-2.0 - 尝试从 OAuth 中获取令牌,获取:“UnhandledPromiseRejectionWarning:错误:redirect_uri_mismatch”
- javascript - HTML 标记中的转义字符
- python - 二维数组的 Numpy 梯度函数首先返回 y 方向的梯度分量,然后返回 x 方向的梯度分量
- excel - 从固定宽度的 txt 文件中只编译一列并包括文件名 Excel-VBA
- javascript - 如何将 JavaScript 变量设置为 textarea 标记的内容?
- ios - “'CardCollectionViewCell' 类型的值没有成员 'flipBack'”
- mysql - phpmyadmin 中 CREATE TRIGGER 的语法错误