0

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

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
michal
  • 1,534
  • 5
  • 28
  • 62

1 Answers1

0

You are sorting values that are of type string. Convert to numeric with parseFloat().

Jeff Matthews
  • 602
  • 2
  • 7
  • 17
  • Ok, I added code `if (!isNaN(a)) {a = parseFloat(a);}else if(!isNaN(b)){b = parseFloat(b);}` after code `tr = tr.sort(function (a, b) {` but still don't sort correctly – michal Jan 29 '18 at 21:17
  • I used this example before, which I think is more intuitive: https://www.w3schools.com/howto/howto_js_sort_table.asp – Jeff Matthews Jan 29 '18 at 21:38