'Sorting alphanumeric column in datatables doesent work
I have some problem to sort a column in jquery data table.
I want to sort the first column ascending/descending.
This is some data from the column (default sorted by desc):
R949
R923
R909
R594
R559
R1017
AS you can see the default Sorting algorithm doesn't work with alphanumeric characters.
This are my settings:
$('#myTable').dataTable({
"aaSorting": [[0, "desc"]],
"paging": false,
"lengthChange": false,
"searching": true,
"ordering": true,
"info": true,
"autoWidth": false
)}
my wish descending result:
R1017
R949
R923
R909
R594
R559
Anybody have some hint what I do wrong? I also tried to use
"columnDefs": [
{"type": "natural", "targets": 0 }]
But this also doesn't work
Solution 1:[1]
The string your are yousing is calculated:
R0xxxxx < R1xxxxx < R2xxxxxx < R3xxxxx < R4xxxxx < R5xxxxx etc ...
You need to do natural sort:
function naturalSort(a, b) {
var ax = [], bx = [];
a.replace(/(\d+)|(\D+)/g, function(_, $1, $2) { ax.push([$1 || Infinity, $2 || ""]) });
b.replace(/(\d+)|(\D+)/g, function(_, $1, $2) { bx.push([$1 || Infinity, $2 || ""]) });
while(ax.length && bx.length) {
var an = ax.shift();
var bn = bx.shift();
var nn = (an[0] - bn[0]) || an[1].localeCompare(bn[1]);
if(nn) return nn;
}
return ax.length - bx.length;
}
test = [
"R12",
"R10",
"R2",
"R1",
"R101",
"R101",
"R10"
];
test.sort(naturalSort);
document.write("<pre>" + JSON.stringify(test,0,3));
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 |
