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.

If you’ve enjoyed this article, you might enjoy my recently published book JavaScript Testing Recipes. It’s full of simple techniques for writing modular, maintainable JavaScript apps in the browser and on the server.