The New Way To Remove Duplicates From An Array In JavaScript

No need for libraries or weird tricks

Piero Borrelli
May 13 · 2 min read

Arrays are fundamental blocks of how we deal with sets of data. We use them every day, not only in JavaScript but in every language. Today, I would like to show you a particular cool trick I found out reading some code.

I believe it can save you some headache when dealing with removing duplicates from your array. Maybe you need to feed a library function with unique array values, or maybe something else.

How can you do that?

Old School Solution

With ECMAScript 5, you could so something like this

The native method filter loops through our array, leaving only those entries that satisfy the function uniqueValues . This function checks if a value is first occurring, if it is, then it’s not a duplicated value.

The ES6 shortened version of this might be something like

The New Way

Why overcomplicating our code? Why writing a function we don’t need after all. ES6 doesn’t force us to use the filter method. Let’s use Set instead.

Same result, fewer lines of code and more clarity. Often times the best solution is hiding behind the corner.

Piero

A note from the Plain English team

Did you know that we have four publications? Show some love by giving them a follow: JavaScript in Plain English, AI in Plain English, UX in Plain English, Python in Plain English — thank you and keep learning! We’ve also launched a YouTube and would love for you to support us by subscribing to our Plain English channel

And as always, Plain English wants to help promote good content. If you have an article that you would like to submit to any of our publications, send an email to submissions@plainenglish.io with your Medium username and what you are interested in writing about and we will get back to you!

JavaScript In Plain English

New articles every day.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store