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 ]

Updated on: 20-Mar-2021

123 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements