1

I have a table that binds data in the format of YYYY-####. In some cases there may be values 2012-456 and 2012-1234. Be default, the 2012-1234 will sort 'before' the 2012-456. If I change the sort to 'numeric', then it throws off other years (ex: would sort in order 2012-456, 2013-555, 2012-1234). I'm guessing I'll have to prepend 0's to the digits after the hyphen if less than 4 digits, but I have not been able to get the sorter to work. I have tried .addParser but I'm not familiar with that and have not been successful. Are there any good articles for what I'm looking for or does anyone know a way to accomplish this?

Here is an image of example data that is sorting incorrectly and would need to sort in order of year (first 4 digits) then number after hyphen:

enter image description here

**Also, the date should have been in a better format obviously, but in this case I'm not able to adjust how that is entered.

deebs
  • 1,390
  • 10
  • 23

1 Answers1

0

After debugging further I was finally able to get .addParser() to work, and condensed the code as much as I could. I guess because I am new(ish) to javascript, I didn't realize that the .length was counting spaces and/or returns in my html.

            $('.tablesorter').tablesorter({
                widgets: ['zebra'],
                headers: {
                    0: {
                        sorter: 'licenseYear'
                    }
                }
            })

            $.tablesorter.addParser({
                id: 'licenseYear',
                is: function (s) {
                    return false;
                },
                format: function (s) {
                    //pad zeros for max length of digits after hyphen
                    var pad = "0000";
                    //replace hyphen with needed zeros to pad number
                    var n = s.replace(/-/, pad.substring(s.length - 5));
                    return n;
                },
                type: 'numeric'
            });

*EDIT: Condensed code with help from this thread about padding left: convert '1' to '0001' in JavaScript

Community
  • 1
  • 1
deebs
  • 1,390
  • 10
  • 23
  • 1
    I have a [fork of tablesorter](http://mottie.github.io/tablesorter/docs/) which uses a natural sort algorithm by default, so you wouldn't even need to use a parser in this case: http://jsfiddle.net/abkNM/5882/ – Mottie May 26 '15 at 18:28
  • Wow, very interesting. What exactly is the "natural sort algorithm" doing? It works great! – deebs May 26 '15 at 19:17
  • 1
    It breaks the content into "chunks", which are basically groups of numbers or letters, and compares them. It is only a little bit slower than a regular sort; the advantages make up for it. The sorting algorithm is from [javascript-natural-sort](https://github.com/overset/javascript-natural-sort) – Mottie May 28 '15 at 05:11