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
Program to pick out duplicate only once - JavaScript
We have an array of literals that contains some duplicate values appearing for many times like this:
const arr = [1, 4, 3, 3, 1, 3, 2, 4, 2, 1, 4, 4];
We are required to write a JavaScript function that takes in this array and pick out all the duplicate entries from the original array and only once.
So, for the above array, the output should be:
[1, 4, 3, 2]
Method 1: Using indexOf and lastIndexOf
This approach checks if an element's first and last occurrence positions are different, indicating it's a duplicate:
const arr = [1, 4, 3, 3, 1, 3, 2, 4, 2, 1, 4, 4];
const pickDuplicate = arr => {
const res = [];
for(let i = 0; i
[1, 4, 3, 2]
Method 2: Using Map for Better Performance
This approach counts occurrences first, then filters duplicates:
const arr = [1, 4, 3, 3, 1, 3, 2, 4, 2, 1, 4, 4];
const pickDuplicateWithMap = arr => {
const countMap = new Map();
// Count occurrences
arr.forEach(item => {
countMap.set(item, (countMap.get(item) || 0) + 1);
});
// Return items that appear more than once
return Array.from(countMap.entries())
.filter(([key, count]) => count > 1)
.map(([key]) => key);
};
console.log(pickDuplicateWithMap(arr));
[1, 4, 3, 2]
Method 3: Using Set and Filter
This approach uses Set to track seen elements and filter for duplicates:
const arr = [1, 4, 3, 3, 1, 3, 2, 4, 2, 1, 4, 4];
const pickDuplicateWithSet = arr => {
const seen = new Set();
const duplicates = new Set();
arr.forEach(item => {
if (seen.has(item)) {
duplicates.add(item);
} else {
seen.add(item);
}
});
return Array.from(duplicates);
};
console.log(pickDuplicateWithSet(arr));
[1, 4, 3, 2]
Performance Comparison
| Method | Time Complexity | Space Complexity | Best For |
|---|---|---|---|
| indexOf/lastIndexOf | O(n²) | O(n) | Small arrays |
| Map | O(n) | O(n) | Large arrays |
| Set | O(n) | O(n) | Best performance |
Conclusion
The Set approach provides the best performance for extracting duplicates from an array. Use the indexOf method for simple cases and Map or Set for larger datasets where performance matters.
