我有一个对象数组,我只想过滤唯一的样式,并且不会重复。
const arrayOfObj = [ {name:'a' , style:'p'} , {name:'b' , style:'q'} , {name:'c' , style:'q'}]
result expected : [ {name:'a' , style:'p'}]发布于 2020-08-14 15:17:01
这里有一个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)
https://stackoverflow.com/questions/63408007
复制相似问题