Natural-order sort in JavaScript

For your delectation and amusement in this new year: the shortest (and possibly slowest…) natural-order sorting method I could come up with:

Array.prototype.naturalSort = function() {
  var p, q, valueOf = function(t) {
    return isNaN(t) ? t.charCodeAt(0) :
        Number(t) - Math.pow(2,32);
  };
  return this.sort(function(a,b) {
    var values = [a,b].map(function(s) {
      return s.toString().toLowerCase()
          .match(/([a-z]|[0-9]+(?:\.[0-9]+)?)/ig);
    });
    a = values[0]; b = values[1];
    for (var i = 0, n = Math.min(a.length, b.length); i < n; i++) {
      p = valueOf(a[i]), q = valueOf(b[i]);
      if (p != q) return p - q;
    }
    return a.length - b.length;
  });
};

I don’t know why, I just had to do this after finding a JS implementation via this article last year which was large, buggy, and littered with global variables…

Please don’t use this, it really is slow. Just an exercise in seeing how short a method I could write.







3 Responses to “Natural-order sort in JavaScript”

[1,2,3,4,5,111,2,4,5,6,1].naturalSort()
> 3,2,4,5,111,2,4,5,6,1,1

timb added these pithy words on Feb 05 08 at 11:31 pm

@timb: I’ve fixed it, it seemed to be a problem with loss of precision when sorting numbers. Thanks for the alert!

James added these pithy words on Feb 06 08 at 1:17 pm

I whipped up another version of a natural sort function in Javascript that works well and is possibly shorter/faster that doesn’t use the charIndex comparisons:

http://www.overset.com/2008/09/01/javascript-natural-sort-algorithm/

num added these pithy words on Sep 01 08 at 8:54 pm

Leave a Reply