patternjavascriptMinor
Ordering cell rows and columns
Viewed 0 times
cellrowscolumnsorderingand
Problem
How can I make this sort faster and better?
function OrderBy(a,b) {
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);
});
};Solution
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);
});Code Snippets
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);
});Context
StackExchange Code Review Q#2006, answer score: 2
Revisions (0)
No revisions yet.