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
Removing duplicates and keep one instance in JavaScript
In JavaScript, you often need to remove duplicate values from an array while keeping only one instance of each value. There are several effective methods to accomplish this task.
Method 1: Using Set (Recommended)
The most modern and efficient approach uses the Set object, which automatically removes duplicates:
const arr = [1, 5, 7, 4, 1, 4, 4, 6, 4, 5, 8, 8]; // Using Set to remove duplicates const uniqueArr = [...new Set(arr)]; console.log(uniqueArr);
[ 1, 5, 7, 4, 6, 8 ]
Method 2: Using filter with indexOf
This approach keeps only the first occurrence of each element by comparing the current index with the first index of the element:
const arr = [1, 5, 7, 4, 1, 4, 4, 6, 4, 5, 8, 8]; const uniqueArr = arr.filter((item, index) => arr.indexOf(item) === index); console.log(uniqueArr);
[ 1, 5, 7, 4, 6, 8 ]
Method 3: In-place Removal with splice
This method modifies the original array by removing duplicates in place:
const arr = [1, 5, 7, 4, 1, 4, 4, 6, 4, 5, 8, 8];
const deleteDuplicate = (arr = []) => {
for(let i = 0; i
[ 7, 1, 6, 4, 5, 8 ]
Comparison
| Method | Performance | Modifies Original | Readability |
|---|---|---|---|
| Set | Fast | No | High |
| filter + indexOf | Slow for large arrays | No | High |
| splice | Medium | Yes | Medium |
Key Points
- The
Setapproach is fastest and most readable for most use cases - The
filter + indexOfmethod preserves the original array but can be slow - The
splicemethod modifies the original array, which may or may not be desired - All methods preserve the order of first occurrences
Conclusion
For removing duplicates while keeping the first instance, use [...new Set(array)] for its simplicity and performance. Choose the splice method only when you need to modify the original array in place.
Advertisements
