Sorting Slickgrid by Multiple Columns?

technomalogical picture technomalogical · Feb 9, 2011 · Viewed 8k times · Source

I just started testing out Slickgrid for a project I'm working on and I'm very impressed with its performance. One requirement I have is sorting on multiple columns. I don't fully have my head wrapped around the Dataview in Slickgrid, so maybe I'm missing something obvious, but is there a way to sort a grid on multiple columns? Even if the UI can't handle sorting by more than one, I would like to be able to call a function with the columns in order, plus ascending or descending. I was able to do this with Datatables, but it doesn't have grouping (another requirement for the project).

In the worst case, I will resort to doing the sorting on the server and serving the content back to the client statically sorted.

Answer

Narayana picture Narayana · Mar 6, 2013

I got it working for dataView with multi-column sort in the way. Was the easiest one to understand too. This is from the example in github, except that I've to pass one more parameter for dataView.sort(). It can always be true, and you can take care of the sort direction in your function.

grid.onSort.subscribe(function (e, args) {
    gridSorter(args.sortCols, dataView);
});

function gridSorter(sortCols, dataview) {
    dataview.sort(function (row1, row2) {
        for (var i = 0, l = sortCols.length; i < l; i++) {
            var field = sortCols[i].sortCol.field;
            var sign = sortCols[i].sortAsc ? 1 : -1;
            var x = row1[field], y = row2[field];
            var result = (x < y ? -1 : (x > y ? 1 : 0)) * sign;
            if (result != 0) {
                return result;
            }
        }
        return 0;
    }, true);
}

Just in case it helps someone.