The If Works This dirt was a building before

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.


4 Comments

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

Posted by timb on 5 February 2008 @ 11pm

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

Posted by James Coglan on 6 February 2008 @ 1pm

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/

Posted by num on 1 September 2008 @ 8pm

Great job, thank you very much !

Posted by Gabor on 18 June 2010 @ 12pm

Leave a Comment