Sorting array based on increasing frequency of elements in JavaScript

We need to write a JavaScript function that sorts an array based on the frequency of elements. Elements with lower frequency appear first, and elements with the same frequency are sorted in ascending order.

Problem

Given an array that might contain duplicates, we want to sort it so that:

  • Elements appearing fewer times come first
  • Elements with the same frequency are sorted in ascending order

For example, if the input is:

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

The expected output is:

[1, 2, 12, 4, 4, 5, 5]

Explanation: Numbers 1, 2, and 12 appear once (lowest frequency), so they come first in ascending order. Then 4 and 5 both appear twice.

Solution

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

const sortByAppearance = (arr = []) => {
    // Count frequency of each element
    const frequency = {};
    arr.forEach(num => {
        frequency[num] = (frequency[num] || 0) + 1;
    });

    // Create array of [element, frequency] pairs
    const freqPairs = Object.keys(frequency).map(num => [
        parseInt(num), 
        frequency[num]
    ]);

    // Sort by frequency first, then by value
    freqPairs.sort((a, b) => {
        if (a[1] === b[1]) {
            return a[0] - b[0]; // Same frequency: sort by value
        }
        return a[1] - b[1]; // Different frequency: sort by frequency
    });

    // Build result array
    const result = [];
    freqPairs.forEach(([num, freq]) => {
        for (let i = 0; i < freq; i++) {
            result.push(num);
        }
    });

    return result;
};

console.log(sortByAppearance(arr));
[ 1, 2, 12, 4, 4, 5, 5 ]

How It Works

The solution follows these steps:

  1. Count Frequencies: Use an object to count how many times each element appears
  2. Create Pairs: Convert the frequency object into an array of [element, frequency] pairs
  3. Sort by Rules: Sort pairs first by frequency, then by element value for ties
  4. Build Result: Reconstruct the array by repeating each element according to its frequency

Alternative Approach Using Map

const sortByFrequency = (arr) => {
    const freqMap = new Map();
    
    // Count frequencies
    arr.forEach(num => {
        freqMap.set(num, (freqMap.get(num) || 0) + 1);
    });
    
    // Sort the original array using custom comparator
    return arr.sort((a, b) => {
        const freqA = freqMap.get(a);
        const freqB = freqMap.get(b);
        
        if (freqA === freqB) {
            return a - b; // Same frequency: sort by value
        }
        return freqA - freqB; // Sort by frequency
    });
};

const testArr = [5, 4, 5, 4, 2, 1, 12];
console.log(sortByFrequency(testArr));
[ 1, 2, 12, 4, 4, 5, 5 ]

Comparison

Approach Time Complexity Space Complexity Pros
Frequency Map + Rebuild O(n log n) O(n) Clear logic, easy to understand
Direct Array Sort O(n log n) O(n) More concise, sorts in-place

Conclusion

Both approaches effectively sort arrays by frequency using frequency counting and custom comparison logic. The Map-based solution offers cleaner syntax and better readability for frequency-based sorting problems.

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

318 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements