I've been working on a function to work within a library for a client, and have been having a lot of trouble keeping the UI responsive during the sorts (even with only a few hundred results).
The function has to resort the entire table each AJAX pagination, as new data may require injection further up. This is what I had so far:
table
is the ID of the table being sorted.sort-attribute
, sort-direction
and the column attribute column
are all pre-set.Using some of the details above I managed to improve performance a bit.
function sorttable(table) {
var context = $('#' + table), tbody = $('#' + table + ' tbody'), sortfield = $(context).data('sort-attribute'), c, dir = $(context).data('sort-direction'), index = $(context).find('thead th[data-column="' + sortfield + '"]').index();
if (!sortfield) {
sortfield = $(context).data('id-attribute');
};
switch (dir) {
case "asc":
tbody.find('tr').sort(function (a, b) {
var sortvala = parseFloat($(a).find('td:eq(' + index + ')').text());
var sortvalb = parseFloat($(b).find('td:eq(' + index + ')').text());
// if a < b return 1
return sortvala < sortvalb ? 1
// else if a > b return -1
: sortvala > sortvalb ? -1
// else they are equal - return 0
: 0;
}).appendTo(tbody);
break;
case "desc":
default:
tbody.find('tr').sort(function (a, b) {
var sortvala = parseFloat($(a).find('td:eq(' + index + ')').text());
var sortvalb = parseFloat($(b).find('td:eq(' + index + ')').text());
// if a < b return 1
return sortvala > sortvalb ? 1
// else if a > b return -1
: sortvala < sortvalb ? -1
// else they are equal - return 0
: 0;
}).appendTo(tbody);
break;
}
In principle the code works perfectly, but it's painfully slow... are there any ways to improve performance?