Created
December 2, 2014 22:44
-
-
Save adamloving/64e79ea47a1c97f08f73 to your computer and use it in GitHub Desktop.
more confusing sorting
This file contains 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
var items = ['0', '000', 0, 1, '001', 'a', 'z', 'A', 'Z', '!', null, undefined]; | |
console.log('sorted', items.sort()); | |
// defaults to string sort null becomes 'null' | |
// sorted [ '!', '0', 0, '000', '001', 1, 'A', 'Z', 'a', null, 'z', undefined ] | |
console.log('string sort', items.sort(function(a, b) { | |
if (a < b) { | |
console.log(typeof(a), a, '<', typeof(b), b, '== true'); | |
return -1; | |
} | |
if (a > b) { | |
console.log(typeof(a), a, '>', typeof(b), b, '== true'); | |
return 1; | |
} | |
// a must be equal to b | |
console.log(typeof(a), a, '(is not > or <)', typeof(b), b); | |
return 0; | |
})); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment