首页 > 解决方案 > 如何删除数组中具有相同值集的对象?

问题描述

给定以下对象数组,我将如何过滤掉

示例输入

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 }
]

标签: javascript

解决方案


结合 ( targetand source) 和 ( sourceand 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))


推荐阅读