仅从对象数组中过滤唯一值javascript

Bha*_*iya 7 javascript ecmascript-6

我有一组对象,我只想过滤独特的样式并且不重复。

const arrayOfObj = [ {name:'a' , style:'p'} , {name:'b' , style:'q'} , {name:'c' , style:'q'}]

result expected : [ {name:'a' , style:'p'}]

Run Code Online (Sandbox Code Playgroud)

hgb*_*123 3

这是一个时间复杂度为 O(n) 的解决方案。您可以迭代所有条目以跟踪条目发生的频率。然后使用该filter()函数过滤只出现一次的。

const arrayOfObj = [
  { name: "a", style: "p" },
  { name: "b", style: "q" },
  { name: "c", style: "q" },
]

const styleCount = {}

arrayOfObj.forEach((obj) => {
  styleCount[obj.style] = (styleCount[obj.style] || 0) + 1
})

const res = arrayOfObj.filter((obj) => styleCount[obj.style] === 1)

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