Created
June 25, 2010 22:09
-
-
Save devinus/453520 to your computer and use it in GitHub Desktop.
A Natural Sorting Comparator for JavaScript's Array.prototype.sort
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 NUMBER_GROUPS = /(-?\d*\.?\d+)/g; | |
var naturalSort = function (a, b) { | |
var aa = String(a).split(NUMBER_GROUPS), | |
bb = String(b).split(NUMBER_GROUPS), | |
min = Math.min(aa.length, bb.length); | |
for (var i = 0; i < min; i++) { | |
var x = parseFloat(aa[i]) || aa[i].toLowerCase(), | |
y = parseFloat(bb[i]) || bb[i].toLowerCase(); | |
if (x < y) return -1; | |
else if (x > y) return 1; | |
} | |
return 0; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment