Skip to content

Instantly share code, notes, and snippets.

@kidsil
Created June 27, 2010 13:44
Show Gist options
  • Save kidsil/454917 to your computer and use it in GitHub Desktop.
Save kidsil/454917 to your computer and use it in GitHub Desktop.
Sorting Table by column
//written by seth from StackOverFlow
//Thanks.
// sorting function for the headers
function th_sorter(a, b) {
// just compare the text
var cmp = $(a).text() > $(b).text();
if (cmp) {
return 1;
}
else {
return $(a).text() === $(b).text() ? -1 : 0;
}
}
var sorted = [], temp=[];
// first sort the 1st row so we can figure out what goes where
$('table tr:first').each(
function(i, tr) {
$(tr).children('td').each( function(idx,node) {
$(node).data('orig', idx);
}).sort( th_sorter ).each( function(idx, node) {
sorted.push( {
html: $(node).html(),
idx: $(node).data('orig')
} );
});
});
// now re-arrange the deck chairs
$('table tr').each( function(i, tr) {
// double each, once to capture and once to move
$(tr).children('td').each( function( idx, node) {
temp[idx] = $(node).html();
}).each( function(idx,node) {
$(node).html( temp[ sorted[idx].idx ] );
});
temp = [];
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment