TL;DR
let uniqueArray = [...new Set([5,5,2,2,2,4,2])];
// [5,2,4]
Enter fullscreen mode
Exit fullscreen mode
...
For further actions, you may consider blocking this person and/or reporting abuse
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.
If you find yourself needing to push unique items to an existing array that was declared with
const
(i.e., you cannot usenew Set()
), then here are two patterns you can use:Method 1 is about 30% faster in my Chrome:
jsbench.me/jzlhpp4thr/1
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!I used to filter and map over an array to remove duplicates. Thanks for sharing this method, Mam.
@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"]
"They both accomplish the same thing here so the choice is yours!"
Well, actually she refers to the spread operator ('...') and Array.from.
In both cases you still have to use new Set.
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.
We will read about it in your post, right? :)
Great tip. Thanks
I have posted a similar thing
How to remove Duplicate elements from the Array
Sai gowtham
// ES5:
Object.keys([1,1,2,2,3,4].reduce((prev,val)=>(prev[val]=1,prev),{}))
// ['1', '2', '3', '4']