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
Counting below / par elements from an array - JavaScript
We are required to write a function that counts how many elements in an array are below or at/above a given number.
Following is our array of Numbers ?
const array = [54,54,65,73,43,78,54,54,76,3,23,78];
For example, if the number is 60, there should be 7 elements below it ?
54,54,43,54,54,3,23
and 5 elements at or above it ?
65,73,78,76,78
Using Array.reduce() Method
The reduce() method processes each array element and accumulates the count of elements below and at/above the threshold.
const array = [54,54,65,73,43,78,54,54,76,3,23,78];
const belowParNumbers = (arr, num) => {
return arr.reduce((acc, val) => {
const legend = ['par', 'below'];
const isBelow = val
{ below: 3, par: 9 }
{ below: 7, par: 5 }
{ below: 8, par: 4 }
How It Works
The function uses a clever technique:
val returnstrueorfalse-
+isBelowconverts boolean to number:truebecomes 1,falsebecomes 0 -
legend[1]is "below",legend[0]is "par" - Each element increments either the "below" or "par" counter
Alternative: Using filter() Method
const array = [54,54,65,73,43,78,54,54,76,3,23,78];
const countBelowPar = (arr, num) => {
const below = arr.filter(val => val val >= num).length;
return { below, par };
};
console.log(countBelowPar(array, 60));
console.log(countBelowPar(array, 70));
{ below: 7, par: 5 }
{ below: 8, par: 4 }
Comparison
| Method | Performance | Readability |
|---|---|---|
reduce() |
Better ? single pass | More complex |
filter() |
Slower ? two passes | More readable |
Conclusion
Use reduce() for better performance with large arrays, or filter() for simpler, more readable code. Both methods effectively count elements below and at/above a threshold value.
Advertisements
