We are required to write a JavaScript function that takes in an array of Numbers as the only argument.
The function should return an array of Numbers that contains the number of elements smaller than each corresponding element in the original array.
For example −
If the input array is −
const arr = [3, 5 4, 1, 2];
Then the output should be −
const output = [2, 4, 3, 0, 1];
Example
const arr = [3, 5, 4, 1, 2]; const smallerNumbersThanCurrent = (arr = []) => { const res=[]; for(let i = 0; i < arr.length; i++){ let count = 0; let j = 0; while(j < arr.length){ if(arr[i] > arr[j]){ count++; j++; }else{ j++; }; }; res.push(count); }; return res; }; console.log(smallerNumbersThanCurrent(arr));
Output
And the output in the console will be −
[2, 4, 3, 0, 1]