tablesorter icon indicating copy to clipboard operation
tablesorter copied to clipboard

Custom sort functions

Open Arrvi opened this issue 10 years ago • 4 comments

It would be great to have possibility to define custom sort (compare) functions. I'm using tablesorter in my recent app, but table that it sorts contains values that are not sorted correctly by default. I need a way to sort non-ascii characters and bring empty cells down to the end of a table.

Arrvi avatar Jul 16 '14 14:07 Arrvi

@Arrvi http://tablesorter.com/docs/example-parsers.html you can add custom parser

BlackScorp avatar Nov 05 '14 08:11 BlackScorp

In my fork of tablesorter, there is an emptyTo option which allows defining where to sort empty cells - check out this demo.

Mottie avatar Jun 13 '15 13:06 Mottie

Unfortunately, it is not possible to add an "autodetecet" sorter, which will be checked before the standard validators.

Example:

	ts.addParser({
        id: "germanShortDate",
        is: function (s) {
            return /\d{1,2}[\.]\d{1,2}[\.]\d{2,4}/.test(s);
        }, format: function (s, table) {
            s = s.replace(/(\d{1,2})[\.](\d{1,2})[\.](\d{2,4})/, "$3/$2/$1");

            return $.tablesorter.formatFloat(new Date(s).getTime());
        }, type: "numeric"
    });

Value: "01.01.2014"

The used parser is: digit :-(

It will be great, if there is a method like: addUserParser() and this parsers will be checkt before the standard

like: unshift

            this.addUserParser = function (parser) {
                var l = parsers.length,
                    a = true;
                for (var i = 0; i < l; i++) {
                    if (parsers[i].id.toLowerCase() == parser.id.toLowerCase()) {
                        a = false;
                    }
                }
                if (a) {
                    parsers.unshift(parser);
                };
            };

tombrain avatar Mar 17 '18 12:03 tombrain

Hi @tombrain!

Unfortunately, it is not possible to add an "autodetecet" sorter, which will be checked before the standard validators.

Yes, it is... that's the purpose of the is callback function (docs). And all custom parsers are checked before the built-in parsers – look at the code in detectParserForColumn.

If you don't want to use a regular expression in the is callback, you could check the column index (if the table doesn't contain any colspans):

$.tablesorter.addParser({
  id: 'myparser',
  is: function(s, table, cell, $cell) {
    // Auto-enable this parser for the 3rd column
    return cell.cellIndex === 2;
  },
  format: function(s, table, cell, cellIndex) {
    // do something to "s"
    return s;
  },
  parsed: false,
  type: 'numeric'
});

Mottie avatar Mar 17 '18 13:03 Mottie