Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get unique values from array of objects

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

like image 301
Guilherme Ferreira Avatar asked Feb 28 '19 14:02

Guilherme Ferreira


People also ask

How do I get unique values from an array of objects?

One way to get distinct values from an array of JavaScript objects is to use the array's map method to get an array with the values of a property in each object. Then we can remove the duplicate values with the Set constructor. And then we can convert the set back to an array with the spread operator.


1 Answers

You could stringify all objects, get the unique JSON and then 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 objects where the keys are in different order, I suggest you to get the entries first, sort this array, stringify it for a set, and then get the 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; }
like image 117
Nina Scholz Avatar answered Oct 05 '22 22:10

Nina Scholz