Skip to content

How to remove duplicates from a JavaScript array

New Course Coming Soon:

Get Really Good at Git

Given an array, how can you remove duplicate values in it?

Let’s say you have an array containing a series of primitive values, for example numbers or strings.

Some of those elements are repeated.

Like in this example:

const list = [1, 2, 3, 4, 4, 3]

We can generare a new array containing the same values, without the duplicates, in this way:

const uniqueList = [...new Set(list)]

uniqueList will now be a new array with the values [1, 2, 3, 4] in it.

How does this work?

Set is a new data structure, introduced in ES6 in 2015, and its main characteristic is to be a container for data that can’t be repeated in the same set. See my full guide on Set here.

By initializing a Set with a destructured array (see the ... operator before new Set()), we pass values and Set automatically removes the duplicates. Then we convert it to an array by wrapping it into square brackets [].

This method works with anything that’s not an object: numbers, strings, booleans, symbols.

Are you intimidated by Git? Can’t figure out merge vs rebase? Are you afraid of screwing up something any time you have to do something in Git? Do you rely on ChatGPT or random people’s answer on StackOverflow to fix your problems? Your coworkers are tired of explaining Git to you all the time? Git is something we all need to use, but few of us really master it. I created this course to improve your Git (and GitHub) knowledge at a radical level. A course that helps you feel less frustrated with Git. Launching May 21, 2024. Join the waiting list!
→ Get my JavaScript Beginner's Handbook
→ Read my JavaScript Tutorials on The Valley of Code
→ Read my TypeScript Tutorial on The Valley of Code

Here is how can I help you: