How to remove duplicates in an array JavaScript

Mo Ibra

Mo Ibra

Dec 24, 2022

In this article we will learn how to remove duplicates elements in an array.

It is very common to remove duplicates elements in an array in JavaScript.


Problem

Now we have a problem, which is that we want to delete the duplicate elements in the array.

Imagine we have an array like this:

[1, 2, 3, 3, 4, 5, 5];

And we want to delete duplicates, so the output will be:

[1, 2, 3, 4, 5]

How to solve this problem?

There is more than one solution to solve this problem:

  • Using forEach method
  • Using new Set
  • Using filter

Remove duplicates in an array using forEach

We can use forEach to remove duplicates in an array.

Example

// Array
const array = [1, 2, 3, 3, 4, 5, 5];

// Unique elements will be here.
const result = [];

// Iterate over elements
array.forEach(ele => {
    if (!result.includes(ele)) {
        result.push(ele);
    }
});

// Result:
console.log(result);

Output

[ 1, 2, 3, 4, 5 ]

How it works?

We just create a new empty array, and then iterate over the old array, adding the elements to the new array but without the duplicate elements.

if (!result.includes(ele)) {
    result.push(ele);
}

Remove duplicates using new Set

We can use new Set() to solve this problem as well.

Set is a special data structure introduced in ES6 that stores a collection of unique values.

As long as the set accepts unique elements only, this means that if we add an array with duplicate elements, it will remove them automatically.

// Array
const array = [1, 2, 3, 3, 4, 5, 5];

// Remove duplicates
const set = new Set(array);

// Result:
console.log(set);

Output

Set(5) { 1, 2, 3, 4, 5 }

Now we need to convert the set to an array using Array.from method.

// Array
const array = [1, 2, 3, 3, 4, 5, 5];

// Remove duplicates
const set = new Set(array);

// Convert set to an array
const result = Array.from(set);

// Result:
console.log(result);

Output

[ 1, 2, 3, 4, 5 ]

Remove duplicates using filter method

We can use filter to solve this problem as well.

// Array
const array = [1, 2, 3, 3, 4, 5, 5];

// Remove duplicates
const duplicates = array.filter((item, index) => {
    if (index === array.indexOf(item)) {
        return item;
    }
});

// Result:
console.log(duplicates);

Output

[ 1, 2, 3, 4, 5 ]

Thank you for reading

Thank you for reading my blog. 🚀

Suggestions For More Articles: