Skip to content

Instantly share code, notes, and snippets.

@devinus
Created June 25, 2010 22:09
Show Gist options
  • Save devinus/453520 to your computer and use it in GitHub Desktop.
Save devinus/453520 to your computer and use it in GitHub Desktop.
A Natural Sorting Comparator for JavaScript's Array.prototype.sort
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