Created
December 11, 2015 19:19
-
-
Save tuscen/8eda87c4d4a685904b15 to your computer and use it in GitHub Desktop.
Sort array of numbers by number of ones in binary representation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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