Es6 a unique array of objects with many

I came across this example to create unique arrays using es6

[ ...new Set(array) ]

It seems to work fine until I tried it with an array of objects and it did not return a unique array.

i.e.

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

Why is this?

+4
source share
3 answers

Why is this?

According to the documentation

The Set object allows you to store unique values ​​of any type, regardless of primitive values ​​or object references .

Now the link for each of these arrays inside this constructor Setwill be different, so the constructor will not be considered a unique value.

+6

:

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

>> [{id:123,value:'test'}]

:

let objRef1 = {id:123,value:'test'} // creates a reference to a location in memory
let objRef2 = {id:123,value:'test'} // creates a new reference to a different place in memory

let uniqueArray = [...new Set([objRef1, objRef2])]

>> [{id:123,value:'test'},{id:123,value:'test'}]
+2

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 it works no matter where you have the new Date () in your object parameter, and then in stringify it is converted to an ISO string.

so then

let arr = [{id:1},{id:1},{id:2}];
uniqueArray(arr) //[{id:1},{id:2}]
0
source

Source: https://habr.com/ru/post/1657492/


All Articles