Rohit Chopra Rohit Chopra - 6 months ago 22
Javascript Question

How to do complex sorting in jQuery tableSorter?

I have a table with the following data:

Cell1 Cell2
Computers 10
Dell 5
IBM 3
Compaq 2
HDDs 12
Seagate 7
Samsung 3
Test 2
Monitors 18
Seagate 7
Samsung 9
Dell 1


Now If I sort by Cell 2, it destroys the format and puts 18,12,10 etc. Is there a way to preserve the rows within a 'parent' from sorting?
For example, if I were to sort by Cell2

Cell1 Cell2
Monitors 18
Seagate 7
Samsung 9
Dell 1
HDDs 12
Seagate 7
Samsung 3
Test 2
Computers 10
Dell 5
IBM 3
Compaq 2


So the child rows are not sorted at all, but the parents are sorted preserving the order of the children.

Answer

It's not that hard to sort some elements, given a parent and some elems:

// custom compare function for sorting by numbers
function sortByNumber( a, b ) {
  if ( + a.innerHTML < b.innerHTML ) return -1;
  else if( + a.innerHTML > b.innerHTML ) return 1;
  else return 0;
}

var parent = ...;

// convert to array, to make sorting possible
var items = jQuery.makeArray( elems );
var len   = items.length;

// do the item sorting by their value
items = items.sort( sortByNumber );

// append them back to the parent in order
for ( var i = 0; i < len; i++ ) {
  parent.appendChild( items[i] );
}

Now you can do it in a loop for the subcategories depending on your markup.