Counting How Many Numbers Are Smaller Than the Current Number in JavaScript


We are required to write a JavaScript function that takes in an array of Numbers.

The function should construct a new array based on the input array.

Each corresponding element of the new array should be the number of elements that are smaller in the original array than that corresponding element.

For example −

If the input array is −

const arr = [2, 7, 3, 1, 56, 4, 7, 8];

Then the output array should be −

const output = [1, 4, 2, 0, 7, 3, 4, 6 ];

Example

Following is the code −

const arr = [2, 7, 3, 1, 56, 4, 7, 8];
const smallerThanCurrent = (arr = []) => {
   let { length } = arr;
   let res = Array(length).fill(0);
   for (let i = 0; i < length; i++){
      for (let j = 0; j < length; ++j){
         if (i != j && arr[i] > arr[j]){
            ++res[i];
         };
      };
   };
   return res;
};
console.log(smallerThanCurrent(arr));

Output

Following is the console output

[
   1, 4, 2, 0,

   7, 3, 4, 6
]

Updated on: 27-Jan-2021

195 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements