0

I'm using this answer here - sort html table with jquery to properly sort my HTML table. However, I would like to simply sort the table with all of the empty TD cells at the bottom. Does anyone have a simple tweak to do this? Here's my exact code -

   $('#sortAnniv').click(function() {
    var table = $('#myTable')
    var rows = table.find('tr:gt(0)').toArray().sort(comparer($(this).index()))
    this.asc = !this.asc
    for (var i = 0; i < rows.length; i++){table.append(rows[i])}
})

function comparer(index) {
    return function(a, b) {
        var valA = getCellValue(a, index), valB = getCellValue(b, index)
        return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.toString().localeCompare(valB)
    }
}
function getCellValue(row, index){ return $(row).children('td').eq(index).text() }
  • Welcome to Stack Overflow. Please provide a Minimal, Reproducible Example: https://stackoverflow.com/help/minimal-reproducible-example – Twisty May 29 '20 at 15:38

1 Answers1

1

just add a case for it

function comparer(index) {
    return function(a, b) {
        var valA = getCellValue(a, index), valB = getCellValue(b, index)
        // Add this line
        if (valA.length === 0) return 1; if (valB.length === 0) return -1;
        return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.toString().localeCompare(valB)
    }
}
ControlAltDel
  • 33,923
  • 10
  • 53
  • 80