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 ?
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.
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.
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}]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With