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
How to count the number of elements in an array below/above a given number (JavaScript)
In JavaScript, we often need to analyze arrays and count elements based on certain conditions. This article shows how to count array elements that fall below or above a given threshold number.
Consider we have an array of numbers like this:
const array = [3.1, 1, 2.2, 5.1, 6, 7.3, 2.1, 9];
We need to write a function that counts how many elements are below and above a given number.
For example, if the number is 5.25, there should be 5 elements below it:
(3.1, 1, 2.2, 5.1, 2.1)
And 3 elements above it:
(6, 7.3, 9)
Note: If any element is equal to the provided number, it should be counted as above the number.
Using Array.reduce() Method
The most efficient approach is to use the reduce() method to iterate through the array once and count both conditions:
const array = [3.1, 1, 2.2, 5.1, 6, 7.3, 2.1, 9];
const countNumbers = (arr, num) => {
return arr.reduce((acc, val) => {
const legend = ['upper', 'lower'];
const isBelow = val < num;
acc[legend[+isBelow]]++;
return acc;
}, {
lower: 0,
upper: 0
});
};
console.log(countNumbers(array, 5.25));
console.log(countNumbers(array, 7));
console.log(countNumbers(array, 1));
{ lower: 5, upper: 3 }
{ lower: 6, upper: 2 }
{ lower: 0, upper: 8 }
How It Works
The function uses these key concepts:
-
reduce()processes each array element and accumulates results -
isBelowcreates a boolean that becomes 0 (false) or 1 (true) when converted to number -
legend[+isBelow]uses the boolean-to-number conversion to select 'upper' or 'lower' - The accumulator object tracks both counts simultaneously
Alternative Approach Using Filter
For better readability, you can use separate filter() operations:
const countNumbersSimple = (arr, num) => {
return {
lower: arr.filter(val => val < num).length,
upper: arr.filter(val => val >= num).length
};
};
console.log(countNumbersSimple(array, 5.25));
{ lower: 5, upper: 3 }
Comparison
| Method | Performance | Readability | Array Passes |
|---|---|---|---|
reduce() |
Better | Moderate | 1 |
filter() |
Slower | Better | 2 |
Conclusion
Use reduce() for better performance when counting array elements based on conditions. The filter() approach offers clearer code but requires two array passes.
