DataTables sorting issue
Issue when display is string and value is an integer
by LittleLama
HTML
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<link rel="stylesheet" href="https://cdn.datatables.net/1.10.16/css/jquery.dataTables.css">
<script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.js"></script>
<body>
<h1>
DataTables issue example
</h1>
<div id="theTable">
<table></table>
</div>
</body>
JavaScript
var persons = [
{id:0,name:"Mickey",nbThings:0,nbOtherThings:7},
{id:1,name:"Mini",nbThings:1,nbOtherThings:6},
{id:2,name:"Donald",nbThings:2,nbOtherThings:5},
{id:3,name:"Picsou",nbThings:3,nbOtherThings:4},
{id:4,name:"Rifi",nbThings:4,nbOtherThings:3},
{id:5,name:"Fifi",nbThings:5,nbOtherThings:2},
{id:6,name:"Loulou",nbThings:20,nbOtherThings:1},
{id:7,name:"Pluto",nbThings:41,nbOtherThings:0}
];
/*Pre processing data*/
var people = [];
for(i in persons) {
var row = [];
row['name']=persons[i].name;
row['things']=displayThings(persons[i]);
row['debugThings']=persons[i].nbThings;
row['debugOtherThings']=persons[i].nbOtherThings;
people.push(row);
}
/*Setting DataTables columns*/
var columns = [
{"title": "Names", data: {
_: "name"
}
},
{"title": "Things", data: {
_: "things.display",
display : "things.display",
filter : "things.value",
sort: "things.value"}
},
{"title": "Debug Things", data: {
_: "debugThings"
}
},
{"title": "Debug Other Things", data: {
_: "debugOtherThings"
}
}
];
/*Calling and filling DataTables*/
table = $("table").DataTable({
retrieve:true,
columns: columns,
order:[[1,'desc']]
});
table.rows.add(people);
table.draw();
/*Formatting function*/
function displayThings(person) {
var str;
str = person.nbThings;
if(person.nbThings !== person.nbOtherThings) {
str += "{"+person.nbOtherThings+"}";
}
return {
display : str,
value : parseInt(person.nbThings,10)
}
}