How to create an array of unique values in JavaScript using Sets

Claire Parker-Jones on May 08, 2018

TL;DR let uniqueArray = [...new Set([5,5,2,2,2,4,2])]; // [5,2,4] Pardon? Sorry for the verbose title - sometimes thi... [Read Full]
markdown guide
 

Good highlight this feature.

However, it maybe worth pointing out that with Set, you can't control the equality operator.

It uses '===', which only work only off same actual object or same value for a primitive.

Which limits the usage somewhat compares to other methods such as map or filter.

 

I used to filter and map over an array to remove duplicates. Thanks for sharing this method, Mam.

 

I will implement this right away in a project I am working on. Although I like the Array.from() better, since it's easier to read. I like easy-to-read code :) Thank you for sharing!

 

@claireparker I have been hanging around in this neighborhood for little over a year now and appreciated a lot of quality content from many different sources but this is the first time I am Googling something and it leads to finding the answer here on this website.

You have a new follower.

 

Is there any difference in performance between Array.from and using the spread operator?

 

"They both accomplish the same thing here so the choice is yours!"

So i dont know if there is some missunderstanding here but as far as i see it they dont work the same as in my case using the spread operator returns

[Set(7)]
0: Set(7) {"anthropological", "security", "surveillance", "technology", "biology", …}

while using Array.from returns

(7) ["anthropological", "security", "surveillance", "technology", "biology", "extra-algorithmic experience", "randomness"]

 
 

Great article and explanations! Thank you for your awesome insight and clear examples!

 
 

What if the elements are deep objects themselves rather than just basic elements like integers and alphabets.

 
code of conduct - report abuse