Reputation: 33
I need to add the sorting functionality for the specific column which contains both positive and negative numbers.
By default, sorting is working as expected. But in my case, i need to sort the positive values only.
Column: Percent
Values: -1% 16% 2% 12% 0%
Expected output: Ascending order: 2% 12% 16% 0% -1%
Descending order: 16% 12% 2% 0% -1%
Any ideas how to do sorting like this?
Upvotes: 1
Views: 2556
Reputation: 85518
You would need to create a custom sorting plugin that does that yourself. You could do as the example below :
function ignoreZeroOrBelow(a, b, high) {
a = parseFloat(a);
a = a>0 ? a : high;
b = parseFloat(b);
b = b>0 ? b : high;
return ((a < b) ? -1 : ((a > b) ? 1 : 0));
}
jQuery.extend( jQuery.fn.dataTableExt.oSort, {
"sort-positive-numbers-only-asc": function (a, b) {
return ignoreZeroOrBelow(a, b, Number.POSITIVE_INFINITY);
},
"sort-positive-numbers-only-desc": function (a, b) {
return ignoreZeroOrBelow(a, b, Number.NEGATIVE_INFINITY)*-1;
}
});
Usage :
var dataTable = $('#example').dataTable({
columnDefs: [
{ type: 'sort-positive-numbers-only', targets : 0 }
],
});
demo -> http://jsfiddle.net/scuo0t6k/
The idea behind the plugin is very simple
-1%
== -1
)Number.POSITIVE_INFINITY
if the value<=0Number.NEGATIVE_INFINITY
if the value<=0By that only values>0 are included when you sort the column.
Upvotes: 3