'Simple custom sorting function for jQuery DataTables
Numeric sorting is not working on my dataset. So I made a custom sorting that converts whole string into number then sorts based on that, but for some reasons its not working. What am i missing here?
$.fn.dataTableExt.oSort["test-desc"] = function (x, y)
{
x = parseInt(x);
y = parseInt(y);
if ( x < y)
{
return 1;
}
return 0;
};
$.fn.dataTableExt.oSort["test-asc"] = function (x, y)
{
x = parseInt(x);
y = parseInt(y);
if ( x > y)
{
return 1;
}
return 0;
}
$('table').DataTable({
"pageLength": 300,
"bLengthChange": false,
"columnDefs": [
{ "type": "test", targets: 3 }
]
});
Both ascending and descending are not working properly. I have checked these functions are being called and properly converting strings to numeric instances.
Solution 1:[1]
jQuery DataTable sort function doesn't return 1 and 0. Instead they return 1 and -1. So modifying the sort function made them work perfectly.
$.fn.dataTableExt.oSort["test-desc"] = function (x, y)
{
x = parseInt(x);
y = parseInt(y);
if ( x > y)
{
return -1;
}
return 1;
};
$.fn.dataTableExt.oSort["test-asc"] = function (x, y)
{
x = parseInt(x);
y = parseInt(y);
if ( x > y)
{
return 1;
}
return -1;
}
Solution 2:[2]
The jQuery DataTable sort function does not look 0 or 1, or for 1 or -1 specifically. It looks for either positive or negative values. So you could just do:
$.fn.dataTableExt.oSort["test-desc"] = function (x, y) {
x = parseInt(x);
y = parseInt(y);
return y - x;
};
$.fn.dataTableExt.oSort["test-asc"] = function (x, y) {
x = parseInt(x);
y = parseInt(y);
return x - y;
};
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Waleed |
Solution 2 | derloopkat |