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


Problem

We are required to write a JavaScript function that takes in an array of numbers. Our function should sort the numbers according to decreasing number of 1s present in the binary representation of those numbers and return the new array.

Example

Following is the code −

 Live Demo

const arr = [5, 78, 11, 128, 124, 68, 6];
const countOnes = (str = '') => {
   let count = 0;
   for(let i = 0; i < str.length; i++){
      const el = str[i];
      if(el === '1'){
         count++;
      };
   };
   return count;
};
const sortByHighBit = (arr = []) => {
   arr.sort((a, b) => countOnes(b) - countOnes(a));
   return arr;
};
console.log(sortByHighBit(arr));

Output

[ 5, 78, 11, 128, 124, 68, 6 ]

Updated on: 19-Apr-2021

85 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements