How To Remove Duplicates From A JavaScript Array?

When dealing with JavaScript arrays, you may encounter scenarios where you need to remove duplicate elements to streamline data processing or ensure data integrity.

To remove duplicates from a JavaScript array, you can use the Set() constructor or filter() and reduce() methods or you can use the forEach loop.

All The Methods #
  1. Using JavaScript Set() Constructor
  2. Using Array filter() Method
  3. Using reduce() Method
  4. Using forEach Loop

1. Using JavaScript Set() Constructor:

One of the simplest and most efficient ways to remove duplicates from an array is by utilizing JavaScript’s Set data structure. Sets are collections of unique values, automatically discarding duplicates when elements are added.

let array = [1, 2, 3, 4, 4, 5, 6, 6];
let uniqueArray = [...new Set(array)];
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5, 6]

By spreading the Set into an array using the spread operator (...), we obtain a new array with duplicate elements removed.

2. Using Array filter() Method:

Another approach involves using the filter() method along with indexOf() to create a new array containing only unique values. This method iterates through each element of the array and filters out duplicates based on their first occurrence index.

let array = [1, 2, 3, 4, 4, 5, 6, 6];
let uniqueArray = array.filter((item, index) => array.indexOf(item) === index);
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5, 6]

This method may not be as efficient for large arrays since it iterates through the array for each element, resulting in a time complexity of O(n^2).

3. Using reduce() Method:

The reduce() method can also be employed to remove duplicates by iterating over the array and building a new array containing only unique values.

let array = [1, 2, 3, 4, 4, 5, 6, 6];
let uniqueArray = array.reduce((acc, currentValue) => {
    if (acc.indexOf(currentValue) === -1) {
        acc.push(currentValue);
    }
    return acc;
}, []);
console.log(uniqueArray); // Output: [1, 2, 3, 4, 5, 6]

4. Using forEach Loop:

Here is an example of removing duplications from an array using forEach loop:

const fruits = ["Mango", "Apple", "Strawberry", "Orange", "Mango"];

const unique = [];
fruits.forEach(i => {
    if(!unique.includes(i)) unique.push(i);
});

console.log(unique);
// Output => [ 'Mango', 'Apple', 'Strawberry', 'Orange' ]

This code snippet utilizes a forEach loop to iterate over the fruits array, checking each element’s presence in the unique array. If an element is not already present, it adds it to the unique array, effectively removing duplicates.