jQuery: sorting lists alphabetically

Sorting lists with jQuery is not a complex task as it could seem. JavaScript provides us with the sort() method of the Array object. All we have to do is to convert our list items into an array of DOM objects and work on the very first letter of their text in order to sort them alphabetically. Let's see the details.

We have the following HTML list:

<ul id="test">
	<li>Aquae</li>
	<li>Zaphiro</li>
	<li>Conundrum</li>
	<li>Facet</li>
	<li>Venus</li>
	<li>Oppidum</li>
	<li>Ideo</li>
	<li>Xeno</li>
	<li>Lambda</li>
	<li>Sicut</li>
</ul>​

We need a plugin that should be able to sort the list items in ascending or descending order. Here's our code:

(function($) {

    $.fn.listSorter = function(options) {
        var that = this;
        var settings = {
            order: 'asc'
        };
        options = $.extend(settings, options);

        var items = $('li', that).get();
        var filtered = '';

        switch (options.order) {
        case 'asc':
        case 'desc':
            break;
        default:
            return new Error('Invalid option');
        }

        return that.each(function() {

            if (options.order == 'asc') {

                var asc = items.sort(function(a, b) {

                    var $text1 = $(a).text();
                    var $text2 = $(b).text();

                    return $text1[0].toLowerCase() > $text2[0].toLowerCase();

                });


                for (var i = 0; i < asc.length; i++) {

                    filtered += '<li>' + $(asc[i]).text() + '</li>';

                }

                $(that).html(filtered);

            } else {

                var desc = items.sort(function(a, b) {

                    var $text1 = $(a).text();
                    var $text2 = $(b).text();

                    return $text1[0].toLowerCase() < $text2[0].toLowerCase();

                });


                for (var j = 0; j < desc.length; j++) {

                    filtered += '<li>' + $(desc[j]).text() + '</li>';

                }

                $(that).html(filtered);

            }

        });
    };

})(jQuery);

The sort() method accepts two parameters which, in our case, are two list items DOM objects. Remember that the jQuery's get() methods turns a set of jQuery elements into their corresponding DOM elements.

To actually sort the list we simply rewrite its HTML content by using a string that will be populated by list items created when looping through the sorted array.

An example:

$('#asc').click(function(e) {
    e.preventDefault();
    $('#test').listSorter();
});

$('#desc').click(function(e) {
    e.preventDefault();
    $('#test').listSorter({
        order: 'desc'
    });
});​

You can see the demo below.

Demo

Live demo

Back to top