Skip to content

Instantly share code, notes, and snippets.

@luanpotter
Last active August 16, 2016 15:32
Show Gist options
  • Save luanpotter/b166a9e2873b0084af5d6a96a412a2bc to your computer and use it in GitHub Desktop.
Save luanpotter/b166a9e2873b0084af5d6a96a412a2bc to your computer and use it in GitHub Desktop.
jquery make any table sortable
$('th').addClass('order'); //hack
$('table').each(function () {
var table = $(this);
var sortOrder = [];
var cmp = function (order, e1, e2) {
return order * e1.localeCompare(e2);
};
var tail = function (a) {
return a.slice(1, a.length);
};
var cmpArray = function (orders, a1, a2) {
var cr = cmp(orders[0], a1[0], a2[0]);
if (cr !== 0 || orders.length === 1) {
return cr;
}
return cmpArray(tail(orders), tail(a1), tail(a2));
};
var sortLines = function (col, order) {
sortOrder.unshift({ col : col, ord : order });
var orders = sortOrder.map(function (o) {
return o.ord;
});
var orderedTrs = table.find('tr').toArray().map(function (tr) {
return $(tr);
}).filter(function (tr) {
return tr.children('th').length === 0;
}).map(function (tr) {
return {
tr : tr,
values: sortOrder.map(function (order) {
return tr.find('td').eq(order.col).text();
})
};
}).sort(function (e1, e2) {
return cmpArray(orders, e1.values, e2.values);
}).map(function (e) {
return e.tr;
});
var firstLine = table.find('tr:first').detach();
table.html('');
table.append(firstLine);
orderedTrs.forEach(function (tr) {
table.append(tr);
});
};
table.find('th.order').each(function () {
var th = $(this);
th.html(th.html() + ' (<a class="up">&darr;</a> | <a class="down">&uarr;</a>)');
th.find('.up').on('click', function () {
sortLines(th.index(), +1);
});
th.find('.down').on('click', function () {
sortLines(th.index(), -1);
});
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment