Wednesday, September 21, 2011

TableSorter Month/Year sorter (Custom Sorting)

Hi all, as usual i have a post for today:)
Yesterday forced to code my own sorter for jquery tablesorter. (http://tablesorter.com)
I have pulled statistics data by date, in this case it was a format Month Abrv. Year such as Apr 2011, Mar 2011.
This sorter can be applied to any of month/year string.
you will need to just replace values the sorter replacing by integers.
and now take a close look at the code:
(this code should cme before you call tablesorter)
      $.tablesorter.addParser({ 
          id: 'months', 
          is: function(s) { 
              return false; 
          }, 
          format: function(s) {
              tmp = s.split(' ');
                            // This line modified by Harel Seligmann - Supporting cross year sorting.
                            // Thanks to Harel for his contribution.     
                            s = tmp[1] + tmp[0].replace(/Jan/, "00").replace(/Feb/, "01").replace(/Mar/, "02").replace(/Apr/, "03").replace(/May/, "04").replace(/Jun/, "05").replace(/Jul/, "06").replace(/Aug/, "07").replace(/Sep/, "08").replace(/Oct/, "09").replace(/Nov/, "10").replace(/Dec/, "11");
              return s;
          }, 
          type: 'digit' 
      });
Now all you need to sort by April 2011, is to replace month names from Apr to April, if you have a string like Apr-2011, so replace in split s.split(' '); to s.split('-');
You can have any month/year format to sort it by.
In current sorter im sorting only months as i poll data per 1 year (2011, 2012, 2013,etc...).
After doing this you are able to call your new sorting method as next:
   $("#tablesorter").tablesorter({
   sortList: [[0,1]], // default sort definition
   widgets: ['zebra'], // theme
   headers: // force sort types
    {
     0 : { sorter: "months" }, //your new sorter name
     1 : { sorter: "currency" },
     2 : { sorter: "currency" },
     3 : { sorter: "currency" }
    }
   }).tablesorterPager({container: $("#pager"), size: 15}); // pager extension
You can tune the parser for you need and post into comments, i will update the post so.
Feel free to ask for other explanations/solutions.

2 comments:

Unknown said...

Thanks for the code above. Found that wouldn't work if you have dates over multiple years. Modified the code so that it makes a number out of both the year and month. So Feb 2013 becomes 201302 and Dec 2012 becomes 201212. Therefore you can sort by multiple years.

Changed line to:
tmp = s.split(' '); s = tmp[1] + tmp[0].replace(/Jan/, "00").replace(/Feb/, "01").replace(/Mar/, "02").replace(/Apr/, "03").replace(/May/, "04").replace(/Jun/, "05").replace(/Jul/, "06").replace(/Aug/, "07").replace(/Sep/, "08").replace(/Oct/, "09").replace(/Nov/, "10").replace(/Dec/, "11");

Harel Seligmann

Unknown said...

@Harel Seligmann Thank you for the conribution.
Have updated the code above with credits to you.