# How to remove duplicates from an array in JavaScript

By Atta Ur Rehman Shah (https://attacomsian.com/about). Published May 8, 2020, updated Oct 16, 2022. Topics: JavaScript.
Canonical URL: https://attacomsian.com/blog/javascript-remove-duplicates-from-array

> A quick article to learn about different ways to remove duplicate elements from an array in vanilla JavaScript.

In JavaScript, there are many ways to remove duplicate elements from an array. You can 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:

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

## Remove duplicates using`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:

```javascript
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 primarily creates a new array populated with all array elements that match a specific condition. Any array element that fails or returns `false`, 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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter#Polyfill) to support older browsers.

## Remove duplicates using `Set` 

A [`Set`](https://attacomsian.com/blog/sets-javascript) 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 initialization time.

Here is an example:

```javascript
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()`](https://attacomsian.com/blog/javascript-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](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Spread_syntax) to perform the `Set` to an array conversion:

```javascript
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, use the `filter()` method.

Read [this guide](https://attacomsian.com/blog/javascript-arrays) to learn more about JavaScript arrays and their methods.
