Numbers smaller than the current number JavaScript


In the given problem statement we have to find the smaller numbers than the current number with the help of Javascript. So for doing this task we will be keeping track of the items and decrement the current number by one to get the desired result.

Understanding the problem statement

The problem statement is asked to write a function which will take an array of integers as input and will return the array of the same length in which every element shows the count of the numbers in the given array which are smaller than the respective item. For example if we have an array [5, 4, 3, 2, 1] and the output should look like [4, 3, 2, 1, 0].

To solve the problem we will traverse the given array and will also compare each item to all the remaining items in the array to get the count of smaller items.

Logic for the above problem

So basically we will use reduce and filter method to iterate the given input array and we will produce a new array with the count of smaller numbers for each item. Javascript's reduce method will accept two arguments. Inside the function we will use the filter method of Javascript to get the new array with all the other items which are less than the current number. And After that we will get its length to get the count of the smaller numbers. Then push the value of count to the result array and return the updated array for the next iteration.

Algorithm

Step 1 − Start the program by defining the array of integer numbers in it.

Step 2 − Now define a function to get a small number than the current number.

Step 3 − Use reduce method to start a callback function as res and an initial value of result array as num.

Step 4 − Inside the function use the filter method to define a new array to store all the smaller numbers of the given array. And we will get the length of smaller numbers.

Step 5 − Push the value of count to the result array and return the updated res array for the next traverse.

Code for the algorithm

const arr = [5, 4, 3, 2, 1];

//function to get the smaller number of current number
const smallerThanCurrent = (arr = []) => {
   return arr.reduce((res, num, i) => {
      const count = arr.filter(otherNum => otherNum < num).length;
      res.push(count);
      return res;
   }, []);
};
console.log(smallerThanCurrent(arr));

Complexity

The above method is using reduce and filter methods of Javascript with O(n^2) time complexity. The reduce method is used to get a more functional programming approach.

Conclusion

We have implemented a solution to the given problem statement to find the count of numbers smaller than the current number in an array. But for big-sized arrays the time complexity of the program is not efficient and we may need to use a more effective way than this program.

Updated on: 18-May-2023

385 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements