DEV Community

Cover image for JavaScript Quick Tip: Quickly Get All Unique Values From An Array
Oliver Jumpertz
Oliver Jumpertz

Posted on • Edited on • Originally published at oliverjumpertz.com

JavaScript Quick Tip: Quickly Get All Unique Values From An Array

The array is still one if not the major data structure in JavaScript. Especially given the fact that Set and Map were introduced way later, many developers have grown comfortable either going with a plain array or using a library for this purpose.

If we now take into account that the array is the only data structure in JavaScript that comes with functional monad methods (map, filter, forEach, etc.), although there is a proposal going on to add these methods to all iterables, it's often more comfortable to go with a plain array for most purposes.

The JavaScript array makes no assumptions about its elements. You can mix and match types, and you can also push duplicates. But what if you only want the unique values of your array?

Gladly, there is a pretty short one-liner that makes it easy for you to filter out duplicates and get an array only containing unique values.

The Code

You can combine the spread operator together with the Set constructor to quickly get all unique values of an array:

const array = [1, 2, 3, 4, 5, 6, 1, 2, 3, 4, 4];

const unique Values = [...new Set(array)];
Enter fullscreen mode Exit fullscreen mode

There is only one issue with this code: The Set relies on the strict equality comparison (===), so it doesn't work well for objects.

The Whole Tip As An Image

If you like visual content more, or if you want to store it for later, I put all this into one single image for you. I hope you like it!

A picture showcasing the above code

Before You Leave

If you would love to read even more content like this, feel free to visit me on Twitter or LinkedIn.

I'd love to count you as my ever-growing group of awesome friends!

Top comments (0)