Sorting Elements with jQuery

Whilst refactoring a jQuery plugin today, I came across a method that placed a list item into an unordered list at a specific point, so that all the items remained in alphabetic order. This long method seemed completely convoluted and slow to me and I decided that there must be an easier way to keep the list in alphabetical order.

There are existing plugins for sorting elements but I never like to just pile on the 3rd party plugins as that means more javascript files to include in a page. Besides, I was sure it should not be difficult.

It soon occured to me that jQuery has the built-in ability to return the elements as an array, using the .get() method and from there, it was not too long before I had my streamlined code to sort the list element alphabetically:

var mylist = $('ul');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
   var compA = $(a).text().toUpperCase();
   var compB = $(b).text().toUpperCase();
   return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });

I utilise the javascript array.sort method to sort the elements in the array and then using the jQuery append() method,  reorder them in the actual list element.

 

66 thoughts on “Sorting Elements with jQuery

  1. Duuuuuude!!! you just saved me $.hit(ton) of hours.
    i was going to go down the rabbit whole of _.sort (lodash) but this is awesome 🙂
    you rock

  2. I have a problem with this function,
    my list is:
    item 1
    … // list of numbers
    item 23
    however, when i sort from 1 -> 9, it’s working, but for double digit postfix it doesn’t!
    any suggestions?

  3. Has any one done any modifications to this that will sort dates correctly? i.e 12/5/2013 – I suppose one needs to know the region to know if they are mm/dd/yyyy or dd/mm/yyyy and do the proper thing.

    I’ve been looking at:
    http://tablesorter.com/docs/

  4. well your display cut out the elements.

    first example is:

    a div class=test_div
    here span with text 1 in it
    span with text 2 in it
    etc
    close div
    last an input button with id=SomeID class=StartSort value=Sort
    ————-
    for the second one

    a div with class=example_two
    span with attribute lang=0, in it Sunday
    span with attribute lang=1, in it Monday
    etc
    close div
    a input button with class=StartSortSecond id=SomeIDSecond value=Sort.

    ——
    sorry for this.

  5. Ok. this is absolutely amazing.

    but here are some stuff to consider:
    1. It needs to work on any combination of elements.
    (ex div->span, td->div etc)
    2. It must sort by other criteria as well because not all the time the sorting is text based.

    So, because your ideea helped so much, i’ll give you mine too…
    __________________________
    ex 1:

    text 1
    text 2
    text 3
    text 4

    your function would be:

    function SortByName(element,child_type){
    var mylist = $(element),listitems = mylist.children(child_type).get();
    listitems.sort(function(a, b) {
    var compA = $(a).text().toUpperCase();
    var compB = $(b).text().toUpperCase();
    return (compA compB) ? 1 : 0;
    })
    $.each(listitems, function(idx, itm) { mylist.append(itm); });
    }

    call it like this:
    $(‘#SomeID’).click(SortByName($(‘.test_div’),’span’));
    or
    $(‘.StartSort’).click(SortByName($(‘.test_div’),’span’));

    but for example you have a display with days of the week like this:

    Sunday
    Monday
    Tuesday
    Wednesday
    Thursday
    Friday
    Saturday

    at this point your function would mess it up… sorting by name is not a good option.

    so we use any attribute of the element we’re displaying as our sort criteria.

    i added lang for span because it won’t mess the validation standard for the page.

    it would be:

    Sunday
    Monday
    Tuesday
    Wednesday
    Thursday
    Friday
    Saturday

    now the function is:

    function SortListByAttr(element,child_type,attribut){
    var mylist = $(element),listitems = mylist.children(child_type).get();
    listitems.sort(function(a, b) {
    var compA = $(a).attr(attribut).toUpperCase();
    var compB = $(b).attr(attribut).toUpperCase();
    return (compA compB) ? 1 : 0;
    })
    $.each(listitems, function(idx, itm) { mylist.append(itm); });
    }

    call it like this:
    $(‘#SomeIDSecond’).click(SortListByAttr($(‘.example_two’),’span’,’lang’));
    or
    $(‘.StartSortSecond’).click(SortListByAttr($(‘.example_two’),’span’,’lang’));

    I hope it helps!

  6. Hi,
    This one not working in IE8.Let me know any solution for resolve this.
    Advance Thanks

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.