

- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Number 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 greaterSmallerNumbers = (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(greaterSmallerNumbers(arr, 3));
Output
Following is the output in the console −
{ greater: 8, smaller: 1 }
- Related Questions & Answers
- Frequency of smaller and larger elements - JavaScript
- Maximum difference between two elements such that larger element appears after the smaller number in C
- Number of Larger Elements on right side in a string in C++
- Numbers smaller than the current number JavaScript
- Unpack elements and set the unpack count larger than the available number of bits in Numpy
- Counting smaller and greater in JavaScript
- Finding the element larger than all elements on right - JavaScript
- Just smaller number with monotone digits in JavaScript
- Number of elements smaller than root using preorder traversal of a BST in C++
- How to multiply each element of a larger vector with a smaller vector in R?
- Program to return number of smaller elements at right of the given list in Python
- Constructing an array of smaller elements than the corresponding elements based on input array in JavaScript
- Find the closest and smaller tidy number in C++
- Program to find maximum difference of any number and its next smaller number in Python
- Sum of smaller elements of nodes in a linked list in C++
Advertisements