Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Remove same values from array containing multiple values JavaScript
In JavaScript, arrays often contain duplicate values that need to be removed. The most efficient modern approach is using Set with the spread operator to create a new array with unique values only.
Example Array with Duplicates
Let's start with an array containing duplicate student names:
const listOfStudentName = ['John', 'Mike', 'John', 'Bob', 'Mike', 'Sam', 'Bob', 'John'];
console.log("Original array:", listOfStudentName);
Original array: [ 'John', 'Mike', 'John', 'Bob', 'Mike', 'Sam', 'Bob', 'John' ]
Using Set with Spread Operator (Recommended)
The Set object automatically removes duplicates, and the spread operator converts it back to an array:
const listOfStudentName = ['John', 'Mike', 'John', 'Bob', 'Mike', 'Sam', 'Bob', 'John'];
const uniqueNames = [...new Set(listOfStudentName)];
console.log("Unique values:", uniqueNames);
Unique values: [ 'John', 'Mike', 'Bob', 'Sam' ]
Using filter() with indexOf()
An alternative approach uses filter() to keep only the first occurrence of each value:
const listOfStudentName = ['John', 'Mike', 'John', 'Bob', 'Mike', 'Sam', 'Bob', 'John'];
const uniqueNames = listOfStudentName.filter((name, index) => listOfStudentName.indexOf(name) === index);
console.log("Unique values:", uniqueNames);
Unique values: [ 'John', 'Mike', 'Bob', 'Sam' ]
Comparison of Methods
| Method | Performance | Readability | Browser Support |
|---|---|---|---|
| Set + Spread | Fast | High | ES6+ |
| filter + indexOf | Slower on large arrays | Medium | All browsers |
Working with Numbers
The same techniques work with numeric arrays:
const numbers = [1, 2, 2, 3, 4, 4, 5];
const uniqueNumbers = [...new Set(numbers)];
console.log("Unique numbers:", uniqueNumbers);
Unique numbers: [ 1, 2, 3, 4, 5 ]
Conclusion
Use [...new Set(array)] for the cleanest and most efficient way to remove duplicates from arrays. The Set approach maintains the original order and works with any data type.
Advertisements
