- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Frequency of smaller and larger elements - 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.
Example
Following is the code −
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
This will produce the following output on console −
{ greater: 8, smaller: 1 }
- Related Articles
- Number of smaller and larger elements - JavaScript
- Frequency distribution of elements - JavaScript
- Maximum difference between two elements such that larger element appears after the smaller number in C
- Finding the element larger than all elements on right - JavaScript
- Looping through and getting frequency of all the elements in an array JavaScript
- Sorting array according to increasing frequency of elements in JavaScript
- Function for counting frequency of space separated elements in JavaScript
- Sorting array based on increasing frequency of elements in JavaScript
- Constructing an array of smaller elements than the corresponding elements based on input array in JavaScript
- Building frequency map of all the elements in an array JavaScript
- Counting smaller and greater in JavaScript
- The larger of two supplementary angles exceeds the smaller by 18 degrees. Find them.
- The larger of two supplementary angles exceeds the smaller by 18°. Find the angles.
- Frequency of elements of one array that appear in another array using JavaScript
- Frequency of vowels and consonants in JavaScript

Advertisements