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
Selected Reading
Counting smaller and greater in JavaScript
Suppose, we have an array of literals like this −
const arr = [3, 5, 5, 2, 23, 4, 7, 8, 8, 9];
We are required to write a JavaScript function that takes in this array and a number, say n, and returns an object representing the count of elements greater than and smaller than n.
Therefore, let’s write the code for this function −
Example
The code for this will be −
const arr = [3, 5, 5, 2, 23, 4, 7, 8, 8, 9];
const smallerLargerNumbers = (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(smallerLargerNumbers(arr, 3));
Output
The output in the console will be −
{ greater: 8, smaller: 1 } Advertisements
