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
Is element repeated more than n times in JavaScript
In JavaScript, you may need to check if any element appears more than a specified number of times in an array. This is useful for data validation, duplicate detection, and enforcing constraints on array contents.
Problem Definition
We need to write a function that takes two arguments:
An Array of literals that may contain repeating elements
A number representing the maximum allowed occurrences (limit)
The function should return false if any element appears more than the limit, and true otherwise.
Using reduce() and every() Methods
The most efficient approach uses reduce() to count occurrences and every() to validate the counts:
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(count => {
return count < 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:
reduce()creates an object where keys are array elements and values are their counts -
Validate counts:
every()checks that all counts are less than the limit
For the array [4, 6, 7, 4, 2, 5, 7, 7, 4, 4, 3], the counts object becomes:
{4: 4, 6: 1, 7: 3, 2: 1, 5: 1, 3: 1}
Alternative Using Map
For better performance with large arrays, you can use a Map:
const validateElementsWithMap = (arr, n) => {
const counts = new Map();
for (const element of arr) {
counts.set(element, (counts.get(element) || 0) + 1);
// Early exit if limit exceeded
if (counts.get(element) >= n) {
return false;
}
}
return true;
};
const testArray = [1, 2, 3, 1, 2, 1];
console.log(validateElementsWithMap(testArray, 3)); // true
console.log(validateElementsWithMap(testArray, 4)); // true
console.log(validateElementsWithMap(testArray, 2)); // false
true true false
Comparison
| Method | Performance | Early Exit | Memory Usage |
|---|---|---|---|
| reduce() + every() | Good | No | Standard |
| Map with loop | Better for large arrays | Yes | Slightly more efficient |
Conclusion
Use reduce() and every() for simple cases, or a Map with early exit for better performance with large datasets. Both approaches effectively validate element frequency constraints in arrays.
