- Related Questions & Answers
- Calculating 1s in binary representation of numbers in JavaScript
- Sorting according to weights of numbers in JavaScript
- Find consecutive 1s of length >= n in binary representation of a number in C++
- XOR counts of 0s and 1s in binary representation in C++
- Sorting objects according to days name JavaScript
- Check if the binary representation of a number has equal number of 0s and 1s in blocks in Python
- Binary representation of next number in C++
- Binary representation of previous number in C++
- Sorting array according to increasing frequency of elements in JavaScript
- Count numbers have all 1s together in binary representation in C++
- 1 to n bit numbers with no consecutive 1s in binary representation?
- Sorting numbers according to the digit root JavaScript
- Binary representation of a given number in C++
- Count number of trailing zeros in Binary representation of a number using Bitset in C++
- Program to find longest distance of 1s in binary form of a number using Python

- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who

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.

Following is the code −

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));

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

Advertisements