I have this code link:
function sortTable(table, col, reverse) {
var tb = table.tBodies[0],
tr = Array.prototype.slice.call(tb.rows, 0),
i;
reverse = -((+reverse) || -1);
tr = tr.sort(function (a, b) {
return reverse
* (a.cells[col].textContent.trim()
.localeCompare(b.cells[col].textContent.trim(), undefined, {numeric: true})
);
});
for(i = 0; i < tr.length; ++i) tb.appendChild(tr[i]);
}
function makeSortable(table) {
var th = table.tHead, i;
th && (th = th.rows[0]) && (th = th.cells);
if (th) i = th.length;
else return;
while (--i >= 0) (function (i) {
var dir = 1;
th[i].addEventListener('click', function () {sortTable(table, i, (dir = 1 - dir))});
}(i));
}
function makeAllSortable(parent) {
parent = parent || document.body;
var t = parent.getElementsByTagName('table'), i = t.length;
while (--i >= 0) makeSortable(t[i]);
}
window.onload = function () {makeAllSortable();};
It is code to sorting records in table, but when I have in my table negative number sorting does not work correctly. For example I have numbers: -132
, -11232
, 0.24
, 0.432
, 2423432
the script sorts in order desc
: 2423432
, 0.432
, 0.24
, -11232
,-132
or asc
: -132
, -11232
, 0.24
, 0.432
, 2423432
.
But it should be correct -11232
, -132
, 0.24
, 0.432
, 2423432
Demo: jsfiddle