![Trending Articles on Technical and Non Technical topics](/images/trending_categories.jpeg)
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
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
Counting smaller numbers after corresponding numbers in JavaScript
Problem
We are required to write a JavaScript function that takes in an array of Numbers as the first and the only argument.
Our function should prepare a new array based on the input array. And each corresponding element of this new array should be the count of elements smaller than the corresponding element in the original array.
For example, if the input to the function is −
const arr = [4, 7, 1, 4, 7, 5, 3, 8, 9];
Then the output should be −
const output = [2, 4, 0, 1, 2, 1, 0, 0, 0];
Output Explanation:
Because number smaller than 4 to its right are 2 (1 and 3), for 7 its 4 (1, 4, 5, 3) and so on.
Example
The code for this will be −
const arr = [4, 7, 1, 4, 7, 5, 3, 8, 9]; const countSmaller = (array = [], num) => array.reduce((acc, val) => { if(val < num){ acc++; }; return acc; }, 0); const smallerArray = (arr = []) => { const res = []; for(let i = 0; i < arr.length; i++){ const el = arr[i]; res[i] = countSmaller(arr.slice(i, arr.length), el); }; return res; }; console.log(smallerArray(arr));
Output
The output in the console will be −
[ 2, 4, 0, 1, 2, 1, 0, 0, 0 ]
Advertisements