portfolio | contact
Thursday the 27th

Multi Column Sort in javascript

Thursday, 1:38 PM
Some time ago, I wrote a function that would generator sort methods that would allow you to sort arrays of objects using a shared child property. One of the obvious short comings was that it would only sort by a single property (or column).

I've been tinkering with an alternative and have finally arrived at something stable.

function getSortMethod(){
var _args = Array.prototype.slice.call(arguments);
return function(a, b){
for(var x in _args){
var ax = a[_args[x].substring(1)];
var bx = b[_args[x].substring(1)];
var cx;

ax = typeof ax == "string" ? ax.toLowerCase() : ax / 1;
bx = typeof bx == "string" ? bx.toLowerCase() : bx / 1;

if(_args[x].substring(0,1) == "-"){cx = ax; ax = bx; bx = cx;}
if(ax != bx){return ax < bx ? -1 : 1;}

Usage is simple. Just supply the column names as arguments, prefixed with +/- to indicate ascending or descending.

ex: items.sort(getSortMethod('+price', '+priority', '-rating', '-reviews'));

Here is a live demo.

◄ back