Computer >> Computer tutorials >  >> Programming >> Javascript

Constructing an array of smaller elements than the corresponding elements based on input array in JavaScript


Problem

We are required to write a JavaScript function that takes in an array of numbers. Our function should construct an output array based on the input array.

For each corresponding element our output array should contain the count of number smaller than that number to its right. Finally, we should return this array.

Example

Following is the code −

const arr = [6, 2, 8, 5, 1, 3];
const buildSmallerArray = (arr = []) => {
   let count;
   let base;
   const res = [];
   for (let i = 0; i < arr.length; i++) {
      base = arr[i];
      count = 0;
      for (let j = i + 1; j < arr.length; j++) {
         if (arr[j] < base) count++;
      };
      res.push(count);
   };
   return res;
};
console.log(buildSmallerArray(arr));

Output

[ 4, 1, 3, 2, 0, 0 ]