Untitled

 avatar
unknown
javascript
2 years ago
1.5 kB
4
Indexable
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]);
}
Editor is loading...