- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP

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

# 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 −

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 ]

- 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
- Sorting array according to increasing frequency of elements in 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 numbers according to the digit root JavaScript
- Count numbers have all 1s together in binary representation in C++
- 1 to n bit numbers with no consecutive 1s in binary representation?
- Binary representation of a given number in C++
- Count number of trailing zeros in Binary representation of a number using Bitset in C++
- Sorting Integers by The Number of 1 Bits in Binary in JavaScript

Advertisements