- Trending Categories
- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies

- 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 Articles
- Calculating 1s in binary representation of numbers in JavaScript
- Find consecutive 1s of length >= n in binary representation of a number in C++
- Sorting according to weights of numbers in JavaScript
- XOR counts of 0s and 1s in binary representation in C++
- Check if the binary representation of a number has equal number of 0s and 1s in blocks in Python
- Sorting objects according to days name JavaScript
- Sorting array according to increasing frequency of elements in JavaScript
- 1 to n bit numbers with no consecutive 1s in binary representation?
- Count numbers have all 1s together in binary representation in C++
- Sorting numbers according to the digit root JavaScript
- Binary representation of next number in C++
- Binary representation of previous number in C++
- Sorting Integers by The Number of 1 Bits in Binary in JavaScript
- Program to find longest distance of 1s in binary form of a number using Python
- Count number of trailing zeros in Binary representation of a number using Bitset in C++

Advertisements