Stable sort in SlickGrid


For those not familiar with SlickGrid, it's a excellent JavaScript grid/spreadsheet component. But there's a problem, while there are some nice examples of the things you can do with it, on the whole the documentation is severely lacking. It's against this lack of documentation that I found myself bashing my head when I discovered the sort in SlickGrid isn't stable.

So SlickGrid doesn't provide a stable sort?

Well, no. Not exactly. SlickGrid actually utilises the JavaScript Array .sort() method, which depending on the browser you're using may or may not be stable. That's because ECMAScript doesn't define whether Array .sort() should be stable or not, so for example (at the time of writing) Firefox uses a stable sort, Chrome does not.

Why do you want Stable Sorts anyway?

Because stable sorts maintain the relative order of records with equal keys, which can be quite important when you're looking at grid/spreadsheet data. For example: Say you've got a grid containing Surnames and Forenames, and in your data you have five people called Smith. With a stable sort on Surname you're guaranteed to always get the Smiths in the same order, with an unstable sort you aren't.

OK, I want a stable sort too. How do I do that in SlickGrid?

First thing to do is pick the type of stable sort you want, I went with the merge sort. More specifically, as I was using jQuery anyway, I went with this one:  Simply include merge-sort.js in your code, as per their instructions, and you'll be able to call .mergeSort() as you would .sort(). Now comes the fun bit, using that in SlickGrid:

grid.onSort.subscribe(function (e, args) { 
    var field = args.sortCol.field;
    data = data.mergeSort(function (a, b) {
       var result = 
           a[field] > b[field] ? 1 :
           a[field] < b[field] ? -1 :
       return args.sortAsc ? result : -result;

That's it, looks simple doesn't it. The above is essentially a slight adjustment of the SlickGrid sorting example at the bottom of their Getting Started page. The 'data' variable is your grid data, 'grid' is your Slick.Grid. The problem is those three lines at the end. It just won't work without them and at the time of writing it's not documented, so I had to figure it out, with the help of Google Groups.

So there you have it, stable sorts in SlickGrid. Easy when you know how.