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
Find distinct elements - JavaScript
We are required to write a JavaScript function that takes in an array of literals, such that some array elements are repeated. We are required to return an array that contains elements that appear only once (not repeated).
For example: If the array is:
const arr = [9, 5, 6, 8, 7, 7, 1, 1, 1, 1, 1, 9, 8];
Then the output should be:
const output = [5, 6];
Using indexOf() and lastIndexOf()
The first approach uses indexOf() and lastIndexOf() to check if an element appears only once. If these methods return the same index, the element is unique.
const arr = [9, 5, 6, 8, 7, 7, 1, 1, 1, 1, 1, 9, 8];
const findDistinct = arr => {
const res = [];
for(let i = 0; i < arr.length; i++){
if(arr.indexOf(arr[i]) !== arr.lastIndexOf(arr[i])){
continue;
};
res.push(arr[i]);
};
return res;
};
console.log(findDistinct(arr));
[5, 6]
Using Map for Frequency Count
A more efficient approach uses a Map to count occurrences, then filters elements that appear exactly once.
const arr = [9, 5, 6, 8, 7, 7, 1, 1, 1, 1, 1, 9, 8];
const findDistinctWithMap = arr => {
const countMap = new Map();
// Count occurrences
arr.forEach(item => {
countMap.set(item, (countMap.get(item) || 0) + 1);
});
// Filter elements that appear only once
return arr.filter(item => countMap.get(item) === 1);
};
console.log(findDistinctWithMap(arr));
[5, 6]
Using filter() with indexOf()
This concise approach combines filter() with indexOf() and lastIndexOf() for a functional programming style.
const arr = [9, 5, 6, 8, 7, 7, 1, 1, 1, 1, 1, 9, 8];
const findDistinctFilter = arr => {
return arr.filter(item => arr.indexOf(item) === arr.lastIndexOf(item));
};
console.log(findDistinctFilter(arr));
[5, 6]
Comparison
| Method | Time Complexity | Readability | Performance |
|---|---|---|---|
| indexOf/lastIndexOf loop | O(n²) | Good | Slower for large arrays |
| Map frequency count | O(n) | Excellent | Best for large arrays |
| filter with indexOf | O(n²) | Excellent | Slower but concise |
Conclusion
Use the Map approach for better performance with large arrays, or the filter method for concise, readable code. All methods correctly identify elements that appear exactly once in an array.
