How to redundantly remove duplicate elements within an array – JavaScript?

Let's say we have an array with duplicate elements like this:

[10, 20, 10, 50, 60, 10, 20, 40, 50]

JavaScript provides several methods to remove duplicate elements from arrays. The most common and efficient approach is using the Set object with the spread operator.

Using Set with Spread Operator (Recommended)

The Set object stores only unique values. Combined with the spread operator, it creates a new array without duplicates:

var originalArray = [10, 20, 10, 50, 60, 10, 20, 40, 50];
var arrayWithNoDuplicates = [...new Set(originalArray)];

console.log("Original array:", originalArray);
console.log("No duplicate values:", arrayWithNoDuplicates);
Original array: [ 10, 20, 10, 50, 60, 10, 20, 40, 50 ]
No duplicate values: [ 10, 20, 50, 60, 40 ]

Using filter() with indexOf()

This method keeps only the first occurrence of each element:

var originalArray = [10, 20, 10, 50, 60, 10, 20, 40, 50];
var noDuplicates = originalArray.filter((item, index) => originalArray.indexOf(item) === index);

console.log("Using filter method:", noDuplicates);
Using filter method: [ 10, 20, 50, 60, 40 ]

Using reduce() Method

The reduce() method can build a new array by checking if each element already exists:

var originalArray = [10, 20, 10, 50, 60, 10, 20, 40, 50];
var noDuplicates = originalArray.reduce((unique, item) => {
    return unique.includes(item) ? unique : [...unique, item];
}, []);

console.log("Using reduce method:", noDuplicates);
Using reduce method: [ 10, 20, 50, 60, 40 ]

Comparison of Methods

Method Performance Readability Browser Support
Set + Spread Fastest High ES6+
filter + indexOf Slower for large arrays Medium ES5+
reduce Slowest Low ES5+

Conclusion

The Set with spread operator is the most efficient and readable method for removing duplicates. Use filter() with indexOf() if you need ES5 compatibility.

Updated on: 2026-03-15T23:19:00+05:30

326 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements