How to Remove Duplicates from an Array in JavaScript

Updated onbyAlan Morel
How to Remove Duplicates from an Array in JavaScript

By default, arrays in JavaScript allow for duplicates, so it is up to you to not add a new element if it already exists in the array.

However, sometimes you start off with an array and need to remove all the duplicates.

In this post, we'll learn how to remove duplicates from an array in JavaScript.

Using a Set

A set in JavaScript is a new collection that stores only unique values in it.

Because every value must be unique in a set, if you try to pass it a duplicate entry, it will not be added.

We can use this to our advantage by creating a set and adding our entire array to it, then converting our set back to an array.

JAVASCRIPT
const array = [1, 2, 2, 3, 3, 3]; const set = new Set(array); const uniqueArray = Array.from(set); console.log(uniqueArray);
BASH
[1, 2, 3]

Alternatively, you can use the spread operator:

JAVASCRIPT
const array = [1, 2, 2, 3, 3, 3]; const set = new Set(array); const uniqueArray = [...set]; console.log(uniqueArray);
BASH
[1, 2, 3]

Either way, we are now left with an array that only contains unique values by taking advantage of the fact that sets only allow for unique values.

Using Filter

Another way to remove duplicates is to use the filter method.

We can just pass true if the current value is unique, and false if it is not.

JAVASCRIPT
const array = [1, 2, 2, 3, 3, 3]; const uniqueArray = array.filter((value, index) => { return array.indexOf(value) === index; }); console.log(uniqueArray);
BASH
[1, 2, 3]

Because the indexOf method will return the first instance the value appears, we can detect if a value is a duplicate because it will return an earlier index, instead of the one we're currently on.

When this happens, we reject this value and return false.

In the end, you're left with an array of only unique values.

Conclusion

In this post, we looked at the two best ways to remove duplicates from an array in JavaScript.

You can either use a set and initialize it with the entire array, or use the filter method to remove duplicates.

Thanks for reading and happy coding!

To learn more about web development, founding a start-up, and bootstrapping a SaaS, follow me on X!
Copyright © 2017 - 2024 Sabe.io. All rights reserved. Made with ❤ in NY.