JavaScript : Removing Duplicates from Arrays in JavaScript

Java Script @ Freshers.in

This article will show how to remove duplicates from an array in JavaScript using the Set object and the filter method:

JavaScript provides a number of ways to remove duplicates from an array. Here are two common methods:

Method 1: Using the Set Object

A Set is a built-in JavaScript object that only allows unique values. Here’s how you can use a Set to remove duplicates from an array:

// Initial array with duplicate values
let array = [1, 2, 3, 4, 5, 5, 2, 4, 3, 6, 7, 8, 9, 9, 8, 7];
// Remove duplicates using Set
let uniqueArray = [...new Set(array)];
console.log(uniqueArray);

ResultĀ 

[
  1, 2, 3, 4, 5,
  6, 7, 8, 9
]

In this code, new Set(array) creates a Set object that automatically removes all duplicate values. The … operator, known as the spread operator, then converts this Set back into an array.

Method 2: Using the Filter Method

The filter method creates a new array with all elements that pass a test provided by a given function. Here’s how to use filter to remove duplicates:

// Initial array with duplicate values
let array = [1, 2, 3, 4, 5, 5, 2, 4, 3, 6, 7, 8, 9, 9, 8, 7];
// Remove duplicates using filter
let uniqueArray = array.filter((value, index, self) => {
    return self.indexOf(value) === index;
});
console.log(uniqueArray);

Output

[
  1, 2, 3, 4, 5,
  6, 7, 8, 9
]

In this code, array.filter() checks each value in the array to see if its first occurrence is equal to its current index. If it is, that means it’s the first time the filter method has encountered that value, so it’s not a duplicate and it’s added to uniqueArray.

While both methods effectively remove duplicates, they have different performance characteristics. The Set object is generally faster and more efficient for large arrays, while the filter method can provide more flexibility with its callback function.

Get more articles on Java Script

Author: user

Leave a Reply