String numeric sort

String numeric sort

sfgroupssfgroups Posts: 10Questions: 0Answers: 0
edited February 2012 in General
Hi,
I have table column data with string and numeric, I want to start this column only by numeric value, I added core to strip out string before sorting, but still its not starting by number.

here is JS Bin sample code with data. I want to sort by second column.

http://live.datatables.net/esajal/4

http://live.datatables.net/esajal/4/edit




[code]
$(document).ready(function() {

jQuery.fn.dataTableExt.oSort['string-num-asc'] = function(x1,y1) {
var x=x1;
var y=y1;
var pattern = /[0-9]+/g;
var matches;
if(x1.length !== 0) {
matches = x1.match(pattern);
x=matches[0];
}
if(y1.length !== 0) {
matches = y1.match(pattern);
y=matches[0];
}
return ((x < y) ? -1 : ((x > y) ? 1 : 0));

};

jQuery.fn.dataTableExt.oSort['string-num-desc'] = function(x1,y1) {

var x=x1;
var y=y1;
var pattern = /[0-9]+/g;
var matches;
if(x1.length !== 0) {
matches = x1.match(pattern);
x=matches[0];
}
if(y1.length !== 0) {
matches = y1.match(pattern);
y=matches[0];
}
$("#debug").html('x='+x+' y='+y);
return ((x < y) ? 1 : ((x > y) ? -1 : 0));

};

var oTable =$('#example').dataTable({"aoColumnDefs": [{
"sType": 'string-num' ,
"aTargets": [ 1 ]
}
]});

} );
[/code]

Replies

  • allanallan Posts: 63,542Questions: 1Answers: 10,476 Site admin
    Looks to me that you just need to convert the numbers to integers, since they are currently strings and thus sorting as such: http://live.datatables.net/esajal/6/edit

    Allan
  • sfgroupssfgroups Posts: 10Questions: 0Answers: 0
    Thanks Allan, it worked.
This discussion has been closed.