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
Counting smaller and greater in JavaScript
In JavaScript, we often need to count elements in an array that are greater than or smaller than a specific value. This is useful for data analysis, filtering, and statistical operations.
Let's say we have an array of numbers and want to count how many elements are greater than and smaller than a given number n.
const arr = [3, 5, 5, 2, 23, 4, 7, 8, 8, 9];
console.log("Array:", arr);
Array: [3, 5, 5, 2, 23, 4, 7, 8, 8, 9]
Using reduce() Method
The most elegant approach uses the reduce() method to iterate through the array once and count both greater and smaller elements simultaneously:
const arr = [3, 5, 5, 2, 23, 4, 7, 8, 8, 9];
const countSmallerAndGreater = (arr, num) => {
return arr.reduce((acc, val) => {
let { greater, smaller } = acc;
if (val > num) {
greater++;
}
if (val < num) {
smaller++;
}
return { greater, smaller };
}, {
greater: 0,
smaller: 0
});
};
console.log("Count for n = 5:", countSmallerAndGreater(arr, 5));
console.log("Count for n = 7:", countSmallerAndGreater(arr, 7));
console.log("Count for n = 3:", countSmallerAndGreater(arr, 3));
Count for n = 5: { greater: 6, smaller: 3 }
Count for n = 7: { greater: 4, smaller: 5 }
Count for n = 3: { greater: 8, smaller: 1 }
Using filter() Method
Alternatively, you can use separate filter() operations for a more readable approach:
const arr = [3, 5, 5, 2, 23, 4, 7, 8, 8, 9];
const countWithFilter = (arr, num) => {
const greater = arr.filter(val => val > num).length;
const smaller = arr.filter(val => val < num).length;
return { greater, smaller };
};
console.log("Using filter for n = 5:", countWithFilter(arr, 5));
Using filter for n = 5: { greater: 6, smaller: 3 }
Using for loop
For better performance with large arrays, a simple for loop is the most efficient:
const arr = [3, 5, 5, 2, 23, 4, 7, 8, 8, 9];
const countWithLoop = (arr, num) => {
let greater = 0;
let smaller = 0;
for (let i = 0; i < arr.length; i++) {
if (arr[i] > num) {
greater++;
} else if (arr[i] < num) {
smaller++;
}
}
return { greater, smaller };
};
console.log("Using loop for n = 5:", countWithLoop(arr, 5));
Using loop for n = 5: { greater: 6, smaller: 3 }
Comparison
| Method | Readability | Performance | Array Passes |
|---|---|---|---|
reduce() |
Good | Good | 1 |
filter() |
Excellent | Slower | 2 |
for loop |
Good | Best | 1 |
Conclusion
The reduce() method provides the best balance of readability and performance by counting both greater and smaller elements in a single pass. Use filter() for maximum readability or a for loop for optimal performance with large datasets.
