Learn how to sort tables dinamically in the client side without needing to refresh your page with JavaScript or jQuery.

Surely you have already checked our Top 7 of the best jQuery and JavaScript plugins to sort tables, and contemplated how easy and quick you can sort tables with the help of a third party plugins. Using a plugin offers and advantage and is that you don't need to mess up with custom code to order a simple Table. Libraries already solve problems like the handling of dates etc.

However in some cases you can't simply use a plugin for this task because either you aren't allowed to or you just want to learn how to it by yourself. In this article we'll share with you 2 ways to sort tables alphabetically using plain JavaScript or using jQuery if you prefer to.

Note

Both of the implementations expect a <thead> (and whose headers are with <th>) and <tbody> structure, so be sure that if you use any of the mentioned methods, this condition is accomplished. Besides, both methods work in the same way, the th elements of your table will become clickable and when they are clicked, the table will be sorted according to its current state (ascending or descending).

Sorting tables with VanillaJS

If you are willing anyway to sort a table without a plugin, then you'll have to write your own code for it. The following JavaScript Object (class-style) offers the makeSortable method that expects as first argument a DOM element of a table specifically:

/**
 * Modified and more readable version of the answer by Paul S. to sort a table with ASC and DESC order
 * with the <thead> and <tbody> structure easily.
 * 
 * https://stackoverflow.com/a/14268260/4241030
 */
var TableSorter = {
    makeSortable: function(table){
        // Store context of this in the object
        var _this = this;
        var th = table.tHead, i;
        th && (th = th.rows[0]) && (th = th.cells);

        if (th){
            i = th.length;
        }else{
            return; // if no `<thead>` then do nothing
        }

        // Loop through every <th> inside the header
        while (--i >= 0) (function (i) {
            var dir = 1;

            // Append click listener to sort
            th[i].addEventListener('click', function () {
                _this._sort(table, i, (dir = 1 - dir));
            });
        }(i));
    },
    _sort: function (table, col, reverse) {
        var tb = table.tBodies[0], // use `<tbody>` to ignore `<thead>` and `<tfoot>` rows
        tr = Array.prototype.slice.call(tb.rows, 0), // put rows into array
        i;

        reverse = -((+reverse) || -1);

        // Sort rows
        tr = tr.sort(function (a, b) {
            // `-1 *` if want opposite order
            return reverse * (
                // Using `.textContent.trim()` for test
                a.cells[col].textContent.trim().localeCompare(
                    b.cells[col].textContent.trim()
                )
            );
        });

        for(i = 0; i < tr.length; ++i){
            // Append rows in new order
            tb.appendChild(tr[i]);
        }
    }
};

The method can be used as shown in the following example:

window.onload = function(){
    TableSorter.makeSortable(document.getElementById("myTable"));
};

Sorting tables with jQuery

With jQuery the process is almost the same, however we can use some utilities like the find method to find the th elements inside your tables. Then we'll attach a listener to every of those elements and add the sorter that uses localeCompare and the isNumber utility of jQuery:

/**
 * mini jQuery plugin based on the answer by Nick Grealy
 * 
 * https://stackoverflow.com/a/19947532/4241030
 */
(function($){
	$.fn.extend({
        makeSortable: function(){
            var MyTable = this;

            var getCellValue = function (row, index){ 
                return $(row).children('td').eq(index).text();
            };
            
            MyTable.find('th').click(function(){
                var table = $(this).parents('table').eq(0);
            
                // Sort by the given filter
                var rows = table.find('tr:gt(0)').toArray().sort(function(a, b) {
                    var index = $(this).index();
                    var valA = getCellValue(a, index), valB = getCellValue(b, index);
            
                    return $.isNumeric(valA) && $.isNumeric(valB) ? valA - valB : valA.localeCompare(valB);
                });
            
                this.asc = !this.asc;
            
                if (!this.asc){
                    rows = rows.reverse();
                }
            
                for (var i = 0; i < rows.length; i++){
                    table.append(rows[i]);
                }
            });
        }
    });
})(jQuery);

It can be used like:

$(function(){
	$("#myTable").makeSortable();
});

After the 2 given examples to sort tables with jQuery or VanillaJS, you surely saw how the localeCompare is used in both of them. The localeCompare() method returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order. This function is in the prototype of the String of the JavaScript engine.

Happy coding !


Senior Software Engineer at Software Medico. Interested in programming since he was 14 years old, Carlos is a self-taught programmer and founder and author of most of the articles at Our Code World.

Sponsors