Home > Software design >  How to sort an html table prioritizing numbers and ignoring strings
How to sort an html table prioritizing numbers and ignoring strings

Time:09-26

I have an html table like this, and a sorting function to sort the "r" column numerically.

function:

function sortTablee(dir) {
    var table, rows, switching, i, x, y, shouldSwitch, switchcount = 0;
    table = document.getElementById("myTable");
    switching = true;
    while (switching) {
        switching = false;
        rows = table.rows;
        for (i = 1; i < (rows.length - 1); i  ) {
            shouldSwitch = false;
            x = rows[i].getElementsByTagName("TD")[1];
            y = rows[i   1].getElementsByTagName("TD")[1];
            if (dir == "asc") {
                if (x.innerHTML > y.innerHTML) {
                    shouldSwitch = true;
                    break;
                }
            } else if (dir == "des") {
                if (x.innerHTML < y.innerHTML) {
                    shouldSwitch = true;
                    break;
                }
            }
        }
        if (shouldSwitch) {
            rows[i].parentNode.insertBefore(rows[i   1], rows[i]);
            switching = true;
            switchcount  ;
        }
    }
}

Everything is fine when sorting descending, but while sorting ascending, instead of showing

   2.5
   4
   5

it prioritizes the dashes, showing the numbers at the bottom. Is there a way to always prioritize and show numbers on top, then get to the dashes?

CodePudding user response:

Maybe check for the '-' and switch it always. So all - are pushed to the back

function sortTablee(dir, w, r, ff, gg) {
    var table, rows, switching, i, x, y, shouldSwitch, switchcount = 0;
    table = document.getElementById("myTable");
    switching = true;
    while (switching) {
        switching = false;
        rows = table.rows;
        for (i = 1; i < (rows.length - 1); i  ) {
            shouldSwitch = false;
            x = rows[i].getElementsByTagName("TD")[1];
            y = rows[i   1].getElementsByTagName("TD")[1];
            if (dir == "asc") {
                if(x.innerHTML == '-'){
                    shouldSwitch = true;
                    break;

                }
                else if (x.innerHTML > y.innerHTML) {
                    shouldSwitch = true;
                    break;
                }
            } else if (dir == "des") {
                if(x.innerHTML == '-'){
                    shouldSwitch = true;
                    break;

                }
                else if (x.innerHTML < y.innerHTML) {
                    shouldSwitch = true;
                    break;
                }
            }
        }
        if (shouldSwitch) {
            rows[i].parentNode.insertBefore(rows[i   1], rows[i]);
            switching = true;
            switchcount  ;
        }
    }
}

  • Related