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
Picking out uniques from an array in JavaScript
Suppose we have an array that contains duplicate elements like this ?
const arr = [1,1,2,2,3,4,4,5];
We are required to write a JavaScript function that takes in one such array and returns a new array. The array should only contain the elements that only appear once in the original array.
Therefore, let's write the code for this function ?
Method 1: Using indexOf() and lastIndexOf()
This approach compares the first and last occurrence of each element. If they're different, the element appears multiple times:
const arr = [1,1,2,2,3,4,4,5];
const extractUnique = arr => {
const res = [];
for(let i = 0; i < arr.length; i++){
if(arr.lastIndexOf(arr[i]) !== arr.indexOf(arr[i])){
continue;
};
res.push(arr[i]);
};
return res;
};
console.log(extractUnique(arr));
[ 3, 5 ]
Method 2: Using filter() with indexOf() and lastIndexOf()
A more concise approach using the filter method:
const arr = [1,1,2,2,3,4,4,5];
const extractUnique = arr => {
return arr.filter((item, index) =>
arr.indexOf(item) === arr.lastIndexOf(item)
);
};
console.log(extractUnique(arr));
[ 3, 5 ]
Method 3: Using Map to Count Occurrences
This method counts each element's occurrences and filters those appearing exactly once:
const arr = [1,1,2,2,3,4,4,5];
const extractUnique = arr => {
const count = new Map();
// Count occurrences
arr.forEach(item => {
count.set(item, (count.get(item) || 0) + 1);
});
// Filter items that appear only once
return arr.filter(item => count.get(item) === 1);
};
console.log(extractUnique(arr));
[ 3, 5 ]
Comparison
| Method | Time Complexity | Readability | Performance |
|---|---|---|---|
| indexOf/lastIndexOf loop | O(n²) | Good | Slower for large arrays |
| filter with indexOf/lastIndexOf | O(n²) | Excellent | Slower for large arrays |
| Map counting | O(n) | Good | Faster for large arrays |
Conclusion
For small arrays, use the filter method for cleaner code. For larger datasets, the Map-based approach offers better performance with O(n) complexity.
