Tell me more ×
Code Review Stack Exchange is a question and answer site for peer programmer code reviews. It's 100% free, no registration required.
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);
    });
};
share|improve this question
2  
'more faster', 'gooder' ...really? – Grant Thomas Apr 20 '11 at 23:40
add comment (requires an account with 50 reputation)

1 Answer

up vote 1 down vote accepted

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);
    });
share|improve this answer
I've seen the map function before, but haven't paid any attention to it. I'll check it out. Thanks! – Phillip Apr 21 '11 at 20:39
add comment (requires an account with 50 reputation)

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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