2
\$\begingroup\$

How can I make this sort faster and better?

function OrderBy(a,b) {
    if (a < b) return -1;
    if (a > b) return 1;
    return 0;
}

SortBy = function($th) {
    var $tbody = $th.closest('tbody');
    var $table = $tbody.parent();
    $tbody.detach();
    $('#Processing').show('fast',function () {
        var column = $th.index();
        var rows = $tbody.find('tr').get();
        rows.sort(function(rowA,rowB) {
            var keyA = $(rowA).children('td').eq(column).text();
            var keyB = $(rowB).children('td').eq(column).text();
            return OrderBy(keyA,keyB);
        });
        $.each(rows, function(index,row) {
            $tbody.append(row);
        });
        $table.append($tbody);
    });
};
\$\endgroup\$
0
2
\$\begingroup\$

You could read the cell texts before sorting, so that it doesn't have to happen repeatedly in the order function:

    var rowsWithText = $tbody.find('tr').map(function() {
      return {
        row: this, 
        text: $(this).children('td').eq(column).text()
      };
    });
    rowsWithText.sort(function(rowA, rowB) {
        return OrderBy(rowA.text, rowB.text);
    });
    $.each(rowsWithText, function(index,row) {
        $tbody.append(row.row);
    });
\$\endgroup\$
1
  • \$\begingroup\$ I've seen the map function before, but haven't paid any attention to it. I'll check it out. Thanks! \$\endgroup\$ Apr 21 '11 at 20:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.