I have a table which needs to be sorted by several columns - let's say music which is sorted by genre, then by artist, album and so on. Or you can sort by artist/album/track. This is what I came up with in jquery:
function tableSort (by) {
var mylist = $('#mainList');
var listitems = $('.row').get();
listitems.sort(function(a, b) {
var cidA=$(a).attr('id');
var cidB=$(b).attr('id');
var i=[1,2,4,3];
var compA=[];
var compB=[];
compA[0]=$(a).find('.album').html();
compB[0]=$(b).find('.album').html();;
compA[1]=$(a).find('.artist').html();
compB[1]=$(b).find('.artist').html();
compA[2]=$(a).find('.genre').html();
compB[2]=$(b).find('.genre').html();
compA[3]=$(a).find('.track').val();
compB[3]=$(b).find('.track').val();
switch (by) {
case 'genre->artist->album':
i=[2,0,1,3];
break;
case 'genre->album->artist':
i=[2,1,0,3];
break;
default:
compA='';
compB='';
}
var comp=(compA[i[0]] < compB[i[0]]) ? -1 : (compA[i[0]] > compB[i[0]]) ? 1 : 0;
if (comp==0) comp=(compA[i[1]] < compB[i[1]]) ? -1 : (compA[i[1]] > compB[i[1]]) ? 1 : 0;
if (comp==0) comp=(compA[i[2]] < compB[i[2]]) ? -1 : (compA[i[2]] > compB[i[2]]) ? 1 : 0;
if (comp==0) comp=(compA[i[3]] < compB[i[3]]) ? -1 : (compA[i[3]] > compB[i[3]]) ? 1 : 0;
return comp;
});
$.each(listitems, function(i, v) {
var id=$(v).attr('id').split('_')[1];
mylist.append(v);
});
}
This works for me with 3-4 orders, but there must be a more elegant and scalable way!