Profile Picture

Prajwal Dhungana

Go Back

How to Remove Duplicates from an Array in JavaScript

Published on Sep 2, 2024

Introduction

In JavaScript, it's common to encounter arrays with duplicate values. In this tutorial, we will explore several methods to remove duplicates and create an array with unique values.

Method 1: Using Set

The simplest way to remove duplicates from an array is by using the Set object, which only allows unique values.

Code Example:

JavaScript Playground
Loading...
Console

Method 2: Using filter and indexOf

Another method is to use the filter method in combination with indexOf. This method checks if the current index of the element is the first occurrence.

Code Example:

JavaScript Playground
Loading...
Console

Method 3: Using reduce

You can also use the reduce method to accumulate unique values in an array.

Code Example:

JavaScript Playground
Loading...
Console

Conclusion

In this tutorial, we explored three different methods to remove duplicates from an array in JavaScript. You can choose the one that best fits your coding style and needs.

Hash Tags:

#JavaScript
#Arrays