Get unique values from array of objects

  • A+
Category:Languages

I have an array of dynamic objects like that:

var arr = [     {state: "FL"},     {state: "NY"},     {state: "FL"},     {gender: "Male"},     {state: "NY"},     {gender: "Female"},     {gender: "Female"},     {year: "1990"} ] 

How can I get just the unique objects?

The desired output is an array containing just the unique objects:

arr = [     {state: "FL"},     {state: "NY"},     {gender: "Male"},     {gender: "Female"},     {year: "1990"} ] 

I'm trying something like that using reduce, but on this way I need know the object key:

arr = arr.reduce((acc, curr) =>      acc.find(e => e['state'] === curr['state']) ? acc : [...acc, curr], []) 

It's not a duplicate because the other questions does not use "dynamic object" to get unique

 


You could stringify all objects, get the unique JSON and convert the strings back to objects.

var array = [{ state: "FL" }, { state: "NY" }, { state: "FL" }, { gender: "Male" }, { state: "NY" }, { gender: "Female" }, { gender: "Female" }, { year: "1990" }],     unique = Array.from(         new Set(array.map(o => JSON.stringify(o))),         s => JSON.parse(s)     );      console.log(unique);
.as-console-wrapper { max-height: 100% !important; top: 0; }

If you have more than one key in the object and because if you have object where the keys are in different order, I suggest to get the entries first, sort this array, stringify it for a set and get new objects back.

var array = [{ foo: 42, state: "FL" }, { state: "FL", foo: 42 }, { state: "FL" }, { state: "NY" }, { state: "FL" }, { gender: "Male" }, { state: "NY" }, { gender: "Female" }, { gender: "Female" }, { year: "1990" }],     unique = Array.from(         new Set(array.map(o => JSON.stringify(Object.entries(o).sort(([a], [b]) => a.localeCompare(b))))),         s => Object.assign({}, ...JSON.parse(s).map(([k, v]) => ({ [k]: v })))     );      console.log(unique);
.as-console-wrapper { max-height: 100% !important; top: 0; }

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: