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

In JavaScript, we often need to count how many elements in an array are smaller than each current element. This creates a new array where each position contains the count of smaller elements from the original array.

Problem Statement

Given an array of numbers, create a new array where each element represents the count of numbers smaller than the corresponding element in the original array.

For example, if the input array is:

[2, 7, 3, 1, 56, 4, 7, 8]

The output should be:

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

Here, 2 has 1 smaller element (1), 7 has 4 smaller elements (2, 3, 1, 4), and so on.

Using Nested Loops

The straightforward approach uses nested loops to compare each element with every other element in the array:

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));
[
  1, 4, 2, 0,
  7, 3, 4, 6
]

Using Array.filter() Method

A more functional approach using the filter() method to count smaller elements:

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

const smallerThanCurrentFilter = (arr = []) => {
    return arr.map(current => 
        arr.filter(num => num < current).length
    );
};

console.log(smallerThanCurrentFilter(arr));
[
  1, 4, 2, 0,
  7, 3, 4, 6
]

How It Works

Both approaches follow the same logic:

  1. For each element in the array, compare it with all other elements
  2. Count how many elements are smaller than the current element
  3. Store this count in the corresponding position of the result array

Comparison

Method Time Complexity Readability Memory Usage
Nested Loops O(n²) Good O(n)
Array.filter() O(n²) Excellent O(n)

Conclusion

Both methods solve the problem with O(n²) time complexity. The filter() approach is more readable and functional, while nested loops offer more control over the iteration process.

Updated on: 2026-03-15T23:19:00+05:30

334 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements