# Sorting Integers by The Number of 1 Bits in Binary in JavaScript

JavascriptWeb DevelopmentFront End Technology

#### JavaScript for beginners

Best Seller

74 Lectures 10 hours

#### Modern Javascript for Beginners + Javascript Projects

Most Popular

112 Lectures 15 hours

#### The Complete Full-Stack JavaScript Course!

Best Seller

96 Lectures 24 hours

We are required to write a JavaScript function that takes in an array of integers as the only argument.

The function should sort the integers present in the array in increasing order based on the 1s present in their binary representation. If two or more numbers have the same number of 1s in their binary, they should be sorted in increasing order according to their magnitude.

For example −

If the input array is −

const arr = [34, 37, 23, 89, 12, 31, 23, 89];

Then the output array will be −

const output = [34, 12, 37, 23, 89, 23, 89, 31];

## Example

Following is the code −

const arr = [34, 37, 23, 89, 12, 31, 23, 89];
const sortByBinary = (arr = []) => {
const calculateOne = (str = '') => {
let res = 0;
for(let i = 0; i < str.length; i++){
if(str[i] === '1'){
res++;
};
};
return res;
}
const sorter = (a, b) => {
const firstCount = calculateOne((a >>> 0).toString(2));
const secondCount = calculateOne((b >>> 0).toString(2));
return firstCount - secondCount;
};
arr.sort(sorter);
};
sortByBinary(arr);
console.log(arr);

## Output

Following is the console output −

[
34, 12, 37, 23,
89, 23, 89, 31
]
Updated on 22-Jan-2021 07:10:16

Advertisements