Skip to content

Instantly share code, notes, and snippets.

@tuscen
Created December 11, 2015 19:19
Show Gist options
  • Select an option

  • Save tuscen/8eda87c4d4a685904b15 to your computer and use it in GitHub Desktop.

Select an option

Save tuscen/8eda87c4d4a685904b15 to your computer and use it in GitHub Desktop.
Sort array of numbers by number of ones in binary representation
function compareByNumOfOnes(a, b) {
return a.match(/1/g).length - b.match(/1/g).length;
}
function solution(array) {
return array.map(item => item.toString(2))
.sort(compareByNumOfOnes)
.map(item => parseInt(item, 2))
}
// Example
// [1, 2, 4, 3] === solution([1, 2, 3, 4])
console.log(solution([1, 2, 3, 4]));
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment