Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

es6 unique array of objects with set

I came across this example for creating unique arrays with es6

[ ...new Set(array) ]

Which seems to work fine until I tried it with an array of objects and it didn't return unique array.

i.e.

let item = [ ...new Set([{id:123,value:'test'},{id:123,value:'test'}]) ];

Why is that ?

like image 678
StevieB Avatar asked Oct 12 '16 11:10

StevieB


People also ask

How do I get a unique 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.

Does set work with arrays?

A Set works on objects and primitives and is useful for preventing identical primitives and re-adding the same object instance. Each array is their own object, so you can actually add two different arrays with the same values. Additionally, there's nothing to prevent an object from being changed once in a set.


1 Answers

you can try to do

uniqueArray = a => [...new Set(a.map(o => JSON.stringify(o)))].map(s => JSON.parse(s))

I know its ugly as hell but in most cases works apart from where you have new Date() in your object param then that on stringify be converted to ISO string.

so then do

let arr = [{id:1},{id:1},{id:2}];
uniqueArray(arr) //[{id:1},{id:2}]
like image 117
Vic Avatar answered Oct 16 '22 13:10

Vic