Sorting according to number of 1s in binary representation using JavaScript

Problem

We need to write a JavaScript function that takes an array of numbers and sorts them in descending order based on the count of 1s in their binary representation.

Understanding Binary Representation

Every number has a binary representation. For example:

  • 5 ? 101 (two 1s)
  • 78 ? 1001110 (four 1s)
  • 11 ? 1011 (three 1s)

Solution Approach

We'll create two functions: one to count 1s in binary representation and another to sort the array.

const arr = [5, 78, 11, 128, 124, 68, 6];

const countOnes = (num) => {
    const binaryStr = num.toString(2);
    let count = 0;
    for(let i = 0; i < binaryStr.length; i++){
        if(binaryStr[i] === '1'){
            count++;
        }
    }
    return count;
};

const sortByHighBit = (arr = []) => {
    return arr.sort((a, b) => countOnes(b) - countOnes(a));
};

// Let's see the binary representations first
console.log("Number ? Binary ? Count of 1s");
arr.forEach(num => {
    console.log(`${num} ? ${num.toString(2)} ? ${countOnes(num)}`);
});

console.log("\nSorted array:", sortByHighBit([...arr]));
Number ? Binary ? Count of 1s
5 ? 101 ? 2
78 ? 1001110 ? 4
11 ? 1011 ? 3
128 ? 10000000 ? 1
124 ? 1111100 ? 5
68 ? 1000100 ? 2
6 ? 110 ? 2

Sorted array: [ 124, 78, 11, 5, 68, 6, 128 ]

Alternative Approach Using Built-in Methods

We can simplify the counting using string methods:

const countOnesSimple = (num) => {
    return num.toString(2).split('1').length - 1;
};

const sortByBitCount = (arr) => {
    return arr.sort((a, b) => countOnesSimple(b) - countOnesSimple(a));
};

const testArr = [5, 78, 11, 128, 124, 68, 6];
console.log("Result:", sortByBitCount([...testArr]));
Result: [ 124, 78, 11, 5, 68, 6, 128 ]

How the Sorting Works

The sort comparison function countOnes(b) - countOnes(a) returns:

  • Positive value: b has more 1s, so b comes first
  • Negative value: a has more 1s, so a comes first
  • Zero: Equal count, original order maintained

Complete Working Example

function sortByBinaryOnes(numbers) {
    const countBinaryOnes = (num) => {
        return num.toString(2).split('').filter(bit => bit === '1').length;
    };
    
    return numbers.sort((a, b) => countBinaryOnes(b) - countBinaryOnes(a));
}

const input = [16, 7, 3, 15, 8, 1];
console.log("Input:", input);
console.log("Sorted by 1s count:", sortByBinaryOnes([...input]));

// Show the binary breakdown
input.forEach(num => {
    const binary = num.toString(2);
    const ones = binary.split('').filter(bit => bit === '1').length;
    console.log(`${num} (${binary}) has ${ones} ones`);
});
Input: [ 16, 7, 3, 15, 8, 1 ]
Sorted by 1s count: [ 7, 15, 3, 1, 16, 8 ]
16 (10000) has 1 ones
7 (111) has 3 ones
3 (11) has 2 ones
15 (1111) has 4 ones
8 (1000) has 1 ones
1 (1) has 1 ones

Conclusion

To sort numbers by their binary 1s count, convert each number to binary using toString(2), count the 1s, and use a custom comparison function. Numbers with more 1s in their binary representation will appear first in the sorted array.

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

233 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements