Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter only unique values from an array of object javascript

I have an array of objects i want to filter only the unique style and is not repeated .

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

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

like image 831
Bhart Supriya Avatar asked Aug 14 '20 07:08

Bhart Supriya


1 Answers

Here is a solution in O(n) time complexity. You can iterate all entries to track how often an entry occurs. And then use the filter() function to filter the ones that occur only once.

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)
like image 117
hgb123 Avatar answered Sep 18 '22 23:09

hgb123