Remove Duplicate Elements from JavaScript Array

d8578raj

Raj

Posted on June 30, 2024

Remove Duplicate Elements from JavaScript Array

Removing duplicate elements from a JavaScript array is a common task that developers often need to perform. JavaScript offers several methods to achieve this, each suitable for different scenarios.

1. Remove Duplicates Using the Set Object

The Set object lets you store unique values of any type, whether primitive values or object references. Converting an array to a Set removes all duplicate elements.

Example:

let numbers = [1, 2, 2, 3, 4, 4, 5];
let uniqueNumbers = [...new Set(numbers)];

// Output: [1, 2, 3, 4, 5]
console.log(uniqueNumbers);
Enter fullscreen mode Exit fullscreen mode

2. Remove Duplicates Using the filter() Method

The filter() method creates a new array with all elements that pass the test implemented by the provided function. By checking the index of each element, duplicates can be filtered out.

Example:

let numbers = [1, 2, 2, 3, 4, 4, 5];
let uniqueNumbers = numbers.filter((value, index, self) => self.indexOf(value) === index);

// Output: [1, 2, 3, 4, 5]
console.log(uniqueNumbers);
Enter fullscreen mode Exit fullscreen mode

3. Remove Duplicates Using the reduce() Method

The reduce() method executes a reducer function on each element of the array, resulting in a single output value. It can be used to accumulate unique elements in an array.

Example:

let numbers = [1, 2, 2, 3, 4, 4, 5];
let uniqueNumbers = numbers.reduce((accumulator, value) => {
    if (!accumulator.includes(value)) {
        accumulator.push(value);
    }
    return accumulator;
}, []);

// Output: [1, 2, 3, 4, 5]
console.log(uniqueNumbers);
Enter fullscreen mode Exit fullscreen mode

4. Remove Duplicates Using forEach() Method

The forEach() method executes a provided function once for each array element. By using an auxiliary object to track unique elements, duplicates can be removed.

Example:

let numbers = [1, 2, 2, 3, 4, 4, 5];
let uniqueNumbers = [];
let seen = {};

numbers.forEach(value => {
    if (!seen[value]) {
        uniqueNumbers.push(value);
        seen[value] = true;
    }
});

// Output: [1, 2, 3, 4, 5]
console.log(uniqueNumbers);
Enter fullscreen mode Exit fullscreen mode

Removing duplicate elements from a JavaScript array can be achieved using various methods. Whether you prefer the simplicity of the Set object, the flexibility of filter(), the power of reduce(), or the combination of map() and filter(), JavaScript provides multiple ways to handle this common task effectively. Each method offers unique advantages, so you can choose the one that best suits your specific needs.

💖 💪 🙅 🚩
d8578raj
Raj

Posted on June 30, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related