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
Selected Reading
How to validate if an element in an array is repeated? - JavaScript
We are required to write a JavaScript function that takes in two arguments:
- An Array, say arr, of literals that may contain some repeating elements.
- A number, say limit.
The function should validate that no element of the array is repeated more than limit number of times. If any element is repeated more than the limit the function should return false, true otherwise.
Using Object to Count Occurrences
The most efficient approach is to use an object to count each element's occurrences, then check if any count exceeds the limit.
const arr = [4, 6, 7, 4, 2, 5, 7, 7, 4, 4, 3];
const validateElements = (arr, n) => {
const counts = arr.reduce((acc, el) => {
acc[el] = (acc[el] + 1) || 1;
return acc;
}, {});
return Object.values(counts).every(c => {
return c < n;
});
};
console.log(validateElements(arr, 3));
console.log(validateElements(arr, 4));
console.log(validateElements(arr, 6));
false false true
How It Works
The function works in two steps:
-
Count occurrences: Uses
reduce()to build an object where keys are array elements and values are their counts. -
Validate counts: Uses
every()to check if all counts are less than the limit.
Alternative Using Map
const validateWithMap = (arr, limit) => {
const countMap = new Map();
for (const element of arr) {
countMap.set(element, (countMap.get(element) || 0) + 1);
// Early return if limit exceeded
if (countMap.get(element) >= limit) {
return false;
}
}
return true;
};
const testArray = [1, 2, 3, 2, 1, 3, 1];
console.log(validateWithMap(testArray, 3)); // true
console.log(validateWithMap(testArray, 2)); // false
true false
Comparison
| Method | Performance | Early Exit | Memory Usage |
|---|---|---|---|
| Object + reduce/every | O(n) | No | Moderate |
| Map with loop | O(n) best case | Yes | Slightly higher |
Conclusion
Both methods effectively validate array element repetition limits. The Map approach offers early exit optimization, while the Object approach is more concise and readable for most use cases.
Advertisements
