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
Upper or lower elements count in an array in JavaScript
When working with arrays of numbers, you may need to count how many elements are above or below a specific threshold value. This is useful for data analysis, filtering, and statistical operations.
Consider we have an array of numbers that looks like this:
const array = [54,54,65,73,43,78,54,54,76,3,23,78];
We need to write a function that counts how many elements in the array are below and above a given number.
For example, if the threshold number is 60:
- Elements below 60: [54,54,43,54,54,3,23] = 7 elements
- Elements above 60: [65,73,78,76,78] = 5 elements
Using Array.reduce() Method
The most efficient approach is to use Array.reduce() to count both categories in a single pass:
const array = [54,54,65,73,43,78,54,54,76,3,23,78];
const countBelowAbove = (arr, threshold) => {
return arr.reduce((acc, val) => {
if (val
{ below: 3, above: 9 }
{ below: 7, above: 5 }
{ below: 8, above: 4 }
Alternative: Using Filter Method
You can also use separate filter() operations for each category:
const array = [54,54,65,73,43,78,54,54,76,3,23,78];
const countWithFilter = (arr, threshold) => {
const below = arr.filter(num => num num >= threshold).length;
return { below, above };
};
console.log(countWithFilter(array, 60));
{ below: 7, above: 5 }
Handling Equal Values
You might want to handle elements equal to the threshold separately:
const array = [54,54,65,73,43,78,54,54,76,3,23,78];
const countBelowEqualAbove = (arr, threshold) => {
return arr.reduce((acc, val) => {
if (val
{ below: 3, equal: 4, above: 5 }
Performance Comparison
| Method | Time Complexity | Space Complexity | Array Passes |
|---|---|---|---|
| Array.reduce() | O(n) | O(1) | 1 |
| Array.filter() | O(n) | O(n) | 2 |
Common Use Cases
- Grade distribution analysis (scores above/below passing grade)
- Sales performance tracking (above/below target)
- Temperature data analysis
- Statistical data categorization
Conclusion
Use Array.reduce() for optimal performance when counting elements above and below a threshold. The reduce method processes the array only once and uses minimal memory compared to multiple filter operations.
