// usage: var mytable = new Sorty(table); (function(){ var Row = function(el) { this.values = $.map($(el).find('td'), function(e) { var el = $(e); var attr = el.attr('data-sort'); return attr ? parseFloat(attr) : el.text(); }); this.el = $(el); }; Row.prototype.value = function(i){ return this.values[i]; }; Row.prototype.get = function(){ return this.el; }; var Sorty = window.Sorty = function(el){ this.el = $(el); this.rows = $.map(this.el.find('tbody tr'), function(el){ return new Row(el); }); this.orders = []; this.body = this.el.find('tbody'); this.headers = this.el.find('thead tr:last-child th'); this.headers.on('click', _.bind(this.click, this)); }; Sorty.prototype.sort = function(by){ if(this.orders[by]) { this.orders[by] *= -1; } else { this.orders[by] = -1; } var order = this.orders[by], ret = []; var sorted = this.rows.sort(function(a, b) { return (a.values[by] < b.values[by] ? 1 : -1) * order; }); var l = sorted.length; for(var i = 0; i < l; i++) ret.push(this.rows[i].get()); return ret; }; Sorty.prototype.click = function(e){ var cur = $(e.currentTarget); var idx = this.headers.index(cur); this.body.html(this.sort(idx)); this.headers.removeClass("sortyUp sortyDown"); if (this.orders[idx] == -1) cur.addClass("sortyUp"); else cur.addClass("sortyDown"); }; })();