How to create a specific sort function in jQuery Tablesorter?

I am using this wonderful version of jQuery Tablesorter: http://mottie.github.com/tablesorter/docs/index.html

Everything works well, but now I have this problem: I have one column in the table that contains the positions of the basketball players. Therefore, I want this column to be sorted logically as follows: PG-SG-SF-PF-C.

I tried to create this custom sorting function - look at my script, column 2:

$(document).ready(function() { $(".stats").tablesorter({ sortInitialOrder: 'desc', sortRestart: true, // Enable use of the characterEquivalents reference sortLocaleCompare: false, // if false, upper case sorts BEFORE lower case ignoreCase: true, headers: { 0: { sortInitialOrder: 'asc' }, 1: { sortInitialOrder: 'asc' }, 2: { textSorter: function(a, b){ var positions = { "PG": 0, "SG": 10, "SF": 20, "PF": 30, "C": 40 }; return ((positions[a] < positions[b]) ? -1 : ((positions[a] > positions[b]) ? 1 : 0)); }, sortInitialOrder: 'asc' } } } ); }); 

However, the column is still sorted alphabetically as a regular text string (C-PF-PG-SF-SG).

Where am I making a mistake? I am not particularly strong in Javascript, so it is probably located somewhere in the sort function. Thanks.

+4
source share
1 answer

I figured this out by adding my own parser, as shown in this question: Sorting images and hyperlinks in a table using the JQuery Sorter plugin

I will copy my script that works the way I want it to work, hope this helps someone:

 $(document).ready(function() { $.tablesorter.addParser({ // set a unique id id: 'positions', is: function(s) { // return false so this parser is not auto detected return false; }, format: function(s) { // format your data for normalization return s.toLowerCase() .replace("pg", "d") .replace("sg", "h") .replace("sf", "m") .replace("pf", "r") .replace("c", "v"); }, // set type, either numeric or text type: 'text' }); $(".stats").tablesorter({ sortInitialOrder: 'desc', sortRestart: true, headers: { 0: { sortInitialOrder: 'asc' }, 1: { sortInitialOrder: 'asc' }, 2: { sorter: 'positions', sortInitialOrder: 'asc' } } } ); }); 
+6
source

Source: https://habr.com/ru/post/1444184/


All Articles