Reputation: 3271
I am using jquery tablesorter. Table sorter having default order like number, special character and alphabets. I need to sort like special character first, number and alphabets.
Check this URL on 3rd column (animal)
jsfiddle.net/Mottie/abkNM/325/
Any help on this ?
Upvotes: 1
Views: 950
Reputation: 86403
The default natural sort breaks up the content into blocks for comparison, but these blocks are set by "chunks" of text characters and numbers. When a non-text/numeric character is encountered it doesn't get broken apart.
So, in your demo the values "#Elephant" and "0Zebra" the sort breaks these values as follows:
#Elephant => [ '#Elephant' ]
0Zebra => [ '0', 'Zebra' ]
when the comparison is done it sees "#Elephant" is non-numeric, but "0" is numeric, so based on ascii comparison, non-numerics (alphabetical characters are assumed) values are greater than numerical values; and thus "#Elephant" gets sorted after "0Zebra".
I know you didn't ask for an explanation, but the easiest way to get around this is to change the sorter. Use the simple text sorter instead (demo):
$('table').tablesorter({
textSorter: {
2: $.tablesorter.sortText
}
});
Update: If you want specific sorting, you'll need to re-order the ascii value. I set up this demo which is specific to the data, it only changes the first character.
var reorderAscii = function(x){
if (x === '') { return x; }
var v = x.charCodeAt(0),
z = x.charCodeAt(0);
if ( z > 90 && z < 97) {
// move [\]^_` to replace ABCDEF
v = v - 26;
} else if (z > 122 && z < 127) {
// move {|}~ to replace GHIJ
v = v - 52;
} else if (z > 47 && z < 58) {
// move 0123456789 to replace KLMNOPQRST
v = v + 27;
}
return z !== v ? String.fromCharCode(v) + x.slice(1) : x;
};
$('table').tablesorter({
theme: 'jui',
headerTemplate: '{content}{icon}',
// ignoreCase must = true
ignoreCase: true,
textExtraction: function(node, table, cellIndex){
var t = $.trim( $(node).text().toLowerCase() );
return cellIndex === 2 ? reorderAscii(t) : t;
},
textSorter: function (a, b) {
if (a == b) { return 0; }
if (a == '') { return 1; }
if (b == '') { return -1; }
return a > b ? 1 : -1;
},
widgets: ['uitheme', 'zebra', 'columns'],
widgetOptions: {
zebra: [
"ui-widget-content even",
"ui-state-default odd"]
}
});
I forgot to mention that using any other sorter beside the alphanumeric sorter, the empty cell and string cell sorting are ignored. I need to include that in the documentation.
Upvotes: 1