Use JavaScript Sets to Return Unique Elements from Array

Using The JavaScript Set Constructor to Return Unique Elements From an Array

Adam Workman
JavaScript in Plain English

--

A Set is an iterable object that holds a collection of unique values. An array is also an iterable object that holds a collection of values, but the values in an array do not have to be unique. We can use the Set constructor to create a new Set from an array, returning only the unique values of that array. How does this method of removing duplicates compare to an iterative loop approach? Let’s take a closer look at both options to find out.

Problem: We need only the unique values from a large array.

Well, a pretty solid solution would be to build a multi-point iterative function that mutates the array and returns the portion of that array that contains the unique elements. Something like this 👇

…and the return value

This returns an array of the unique values, as we would expect, and it does so with a time complexity of O(n). This is a great solution and would work in a wide variety of applications, but let’s take a look at another option.

As stated at the beginning of this article, we can also use the Set constructor to create a new Set from an array. We can use this Set to return only the unique values of that array. Let’s see what that looks like.

… the return value

As you can see, the return value looks very similar, the only difference is that it hasn't been sorted. But how does it compare in terms of performance? We can take a very high level look at this by checking how long each function takes to run. This can be accomplished by using console.time() and conlosle.timeEnd(). Let’s see how they compare.

First, our loop:

Not too bad. After running the function several times, it looks like our iterative loop takes about 0.15 milliseconds to return the unique values from the given array.

And what about using the Set constructor to accomplish the same thing?

Well, it looks like 0.05 milliseconds is the average time it takes the Set constructor to accomplish the same task with the same input. That’s 300% faster than our iterative loop method!

Conclusion

Not only is using the Set constructor three times faster, it uses fewer lines of code and, in my opinion, it’s more readable than the iterative loop method. It may not fly in a technical interview (it totally should), but I know which method I will be using in my real world applications. I hope this was helpful and gives you a good jumping off point for learning more about JavaScript Set. Have fun and happy coding!

More content at plainenglish.io

--

--