How to remove duplicates from an array in 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:

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

Remove duplicates usingfilter() 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 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 to support older browsers.

Remove duplicates using Set

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 initialization time.

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 = [ 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 to learn more about JavaScript arrays and their methods.

✌️ Like this article? Follow me on Twitter and LinkedIn. You can also subscribe to RSS Feed.

You might also like...

Digital Ocean

The simplest cloud platform for developers & teams. Start with a $200 free credit.

Buy me a coffee ☕

If you enjoy reading my articles and want to help me out paying bills, please consider buying me a coffee ($5) or two ($10). I will be highly grateful to you ✌️

Enter the number of coffees below:

✨ Learn to build modern web applications using JavaScript and Spring Boot

I started this blog as a place to share everything I have learned in the last decade. I write about modern JavaScript, Node.js, Spring Boot, core Java, RESTful APIs, and all things web development.

The newsletter is sent every week and includes early access to clear, concise, and easy-to-follow tutorials, and other stuff I think you'd enjoy! No spam ever, unsubscribe at any time.