DEV Community

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] Enter fullscreen mode Exit fullscreen mode ...
Collapse
 
xngwng profile image
Xing Wang

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.

Collapse
 
tohodo profile image
Tommy

If you find yourself needing to push unique items to an existing array that was declared with const (i.e., you cannot use new Set()), then here are two patterns you can use:

// Given this...
const arr = ['A', 'B', 'C'];
const itemsToAdd = ['C', 'D', 'E'];

// Both methods will produce arr = ['A', 'B', 'C', 'D', 'E']

// Method 1:
itemsToAdd.forEach((i) => {
  if (!arr.includes(i)) {
    arr.push(i);
  }
});

// Method 2:
arr.push(...itemsToAdd.filter((i) => !arr.includes(i)));
Enter fullscreen mode Exit fullscreen mode

Method 1 is about 30% faster in my Chrome:
jsbench.me/jzlhpp4thr/1

Collapse
 
itsmeseb profile image
sebkolind

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!

Collapse
 
mehraas profile image
Ashish Mehra • Edited

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

Collapse
 
jochemstoel profile image
Jochem Stoel

@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.

Collapse
 
seth10 profile image
Seth T

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

Collapse
 
kimlongbtc profile image
KimLongUn

"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"]

Collapse
 
neovortex profile image
Neocortexxx • Edited

"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.

Collapse
 
javascripterika profile image
JavaScriptErika

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

Collapse
 
ayoalfonso profile image
AyoAlfonso

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

Collapse
 
nutondev profile image
nuton.dev

We will read about it in your post, right? :)

Collapse
 
evangelistaagil profile image
Marcelo Faundez

Great tip. Thanks

Collapse
 
sait profile image
Sai gowtham
Collapse
 
wbarath profile image
William Barath

// ES5:
Object.keys([1,1,2,2,3,4].reduce((prev,val)=>(prev[val]=1,prev),{}))
// ['1', '2', '3', '4']