How to remove duplicates from an array in JavaScript

published: 07 Sep 2022

2 min read

How to remove duplicates from an array in JavaScript

In vanilla JavaScript, there are multiple ways available to remove duplicate elements from an array. You can either use the filter() method or the Set object to remove all repeated items from an array.

Let us say that we have the following array that contains duplicate elements:

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

filter() Method

The following example demonstrates how you can use the filter() method to remove all duplicate elements from the above array and returns only unique values:

const unique = numbers.filter((value, index) => {
    return numbers.indexOf(value) === index;
});

// print unique array
console.log(unique); // [ 1, 2, 3, 4, 5, 6 ]

The filter() method basically creates a new array populated with all array elements that pass a certain condition. Any element that fails or returns false, it will be excluded from the filtered array.

This approach works in all modern browsers, and Internet Explorer 9 and higher. However, you can use a polyfill to support older browsers.

Set Object

A Set is a special object type introduced in ES6 that stores a collection of unique values. Since each value stored in a Set must be unique, passing any duplicate item will be removed automatically at the time of initialization.

Here is an example:

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

// remove duplicates
const unique = Array.from(new Set(numbers));

// print unique array
console.log(unique); // [ 1, 2, 3, 4, 5, 6 ]

In the above example, we have to use the Array.from() method to convert the Set back to an array. This step is necessary because a Set is not an array.

Alternatively, you could also use the spread operator to perform the Set to an array conversion:

const unique = [...new Set(numbers)];

This approach will only work in modern browsers and in a Node.js application. If you want to support old browsers, better to use the filter() methods.

Take a look at this guide to learn more about JavaScript arrays and their methods.

How to remove duplicates from an array in JavaScript | Coding Tips And Tricks

Are we missing something?  Help us improve this article. Reach out to us.

Are you looking for other code tips?

Check out what's on in the category: javascript, nodejs, programming
Check out what's on in the tag: javascript, nodejs, programming, array