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
Checking for uniqueness in an array in JavaScript
We are required to write a JavaScript function that takes in an array of numbers as the first and the only argument. The function should return true if all the numbers in the array appear only once (i.e., all the numbers are unique), and false otherwise.
For example ?
If the input array is ?
const arr = [12, 45, 6, 34, 12, 57, 79, 4];
Then the output should be ?
const output = false;
because the number 12 appears twice in the array.
Method 1: Using indexOf() and lastIndexOf()
This approach checks if the first occurrence and last occurrence of each element are at the same position.
const arr = [12, 45, 6, 34, 12, 57, 79, 4];
const containsAllUnique = (arr = []) => {
const { length: l } = arr;
for(let i = 0; i < l; i++){
const el = arr[i];
const firstIndex = arr.indexOf(el);
const lastIndex = arr.lastIndexOf(el);
if(firstIndex !== lastIndex){
return false;
}
}
return true;
};
console.log(containsAllUnique(arr));
false
Method 2: Using Set (Most Efficient)
A Set automatically removes duplicates, so comparing the Set size with the original array length tells us if all elements are unique.
const arr1 = [12, 45, 6, 34, 12, 57, 79, 4];
const arr2 = [1, 2, 3, 4, 5];
const isAllUnique = (arr) => {
return new Set(arr).size === arr.length;
};
console.log(isAllUnique(arr1)); // false - has duplicates
console.log(isAllUnique(arr2)); // true - all unique
false true
Method 3: Using filter() with indexOf()
This method filters elements that appear at their first occurrence position.
const arr = [12, 45, 6, 34, 12, 57, 79, 4];
const hasAllUnique = (arr) => {
return arr.filter((item, index) => arr.indexOf(item) === index).length === arr.length;
};
console.log(hasAllUnique(arr));
false
Comparison
| Method | Time Complexity | Space Complexity | Readability |
|---|---|---|---|
| indexOf/lastIndexOf | O(n²) | O(1) | Good |
| Set | O(n) | O(n) | Excellent |
| filter/indexOf | O(n²) | O(n) | Good |
Conclusion
The Set method is the most efficient and readable approach for checking array uniqueness. It has O(n) time complexity and provides a clean, one-line solution for duplicate detection.
