Untitled

mail@pastecode.io avatar
unknown
javascript
7 months ago
1.5 kB
1
Indexable
Never
function sortDate(n) {
    var table,
        rows,
        switching,
        i,
        x,
        y,
        shouldSwitch,
        dir,
        switchcount = 0;
    table = document.getElementById("myTable");
    switching = true;
    dir = "asc";
    while (switching) {
        switching = false;
        rows = table.rows;
        for (i = 1; i < rows.length - 1; i++) {
            shouldSwitch = false;
            x = rows[i].getElementsByTagName("TD")[n].innerText;
            y = rows[i + 1].getElementsByTagName("TD")[n].innerText;
            if (dir == "asc") {
                if (convertDateToInteger(x) > convertDateToInteger(y)) {
                    shouldSwitch = true;
                    break;
                }
            } else if (dir == "desc") {
                if (convertDateToInteger(x) < convertDateToInteger(y)) {
                    shouldSwitch = true;
                    break;
                }
            }
        }
        if (shouldSwitch) {
            rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
            switching = true;
            switchcount++;
        } else {
            if (switchcount == 0 && dir == "asc") {
                dir = "desc";
                switching = true;
            }
        }
    }
}

function convertDateToInteger(dateString) {
    var parts = dateString.split("/");
    return parseInt(parts[2] + parts[1] + parts[0]);
}