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
Filtering out the non-unique value to appear only once in JavaScript
We have an array that contains some duplicate values appearing multiple times. We need to extract only the elements that appear more than once in the array, but show each duplicate element only once in the result.
const arr = [1, 4, 3, 3, 1, 3, 2, 4, 2, 1, 4, 4];
console.log("Original array:", arr);
Original array: [1, 4, 3, 3, 1, 3, 2, 4, 2, 1, 4, 4]
We need to write a JavaScript function that filters out elements that appear multiple times and returns each duplicate element only once.
For the above array, the expected output should be:
[1, 4, 3, 2]
Using indexOf() and lastIndexOf() Method
This approach checks if the first occurrence and last occurrence of an element are different, indicating duplicates:
const arr = [1, 4, 3, 3, 1, 3, 2, 4, 2, 1, 4, 4];
const removeDuplicate = arr => {
const res = [];
for(let i = 0; i
[1, 4, 3, 2]
Using Set and Filter Method
A more modern approach using Set to track seen elements and filter for duplicates:
const arr = [1, 4, 3, 3, 1, 3, 2, 4, 2, 1, 4, 4];
const getDuplicates = 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(getDuplicates(arr));
[4, 3, 1, 2]
Using Object to Count Occurrences
This method counts each element's frequency and filters elements that appear more than once:
const arr = [1, 4, 3, 3, 1, 3, 2, 4, 2, 1, 4, 4];
const findDuplicates = arr => {
const count = {};
// Count occurrences
arr.forEach(item => {
count[item] = (count[item] || 0) + 1;
});
// Filter elements that appear more than once
return Object.keys(count)
.filter(key => count[key] > 1)
.map(Number);
};
console.log(findDuplicates(arr));
[1, 4, 3, 2]
Comparison
| Method | Time Complexity | Readability | Performance |
|---|---|---|---|
| indexOf/lastIndexOf | O(n²) | Good | Slower for large arrays |
| Set-based | O(n) | Excellent | Fast |
| Object counting | O(n) | Good | Fast |
Conclusion
The Set-based approach is most efficient for finding duplicate elements, offering O(n) time complexity. Use indexOf/lastIndexOf for smaller arrays when simplicity is preferred.
