JQuery sort()

11 Feb
2009

JQuery. Write less, do more

JQuery. Write less, do more

Today I was trying to figure out how to sort a set of list item elements alphabetically using JQuery. Seems simple enough but after searching around I couldn’t find any ready made solution. The best I could find was JQuery Table Sort (which is a nice sorting package but not what I was looking for). After playing around for a bit, this is what I came up with:

jQuery.fn.sort = function() {
   return this.pushStack( [].sort.apply( this, arguments ), []);
 };

function sortAlpha(a,b){
    return a.innerHTML > b.innerHTML ? 1 : -1;
};

$('ol li').sort(sortAlpha).appendTo('ol');

Short and sweet. The result is a in place sort based off the innerHTML alphabetically.

9 Responses to JQuery sort()

Avatar

Martijn Laarman

May 8th, 2009 at 7:16 am

Good job on a lean solution, jquery really needs a sort method like this one :)

Avatar

mclemmens

August 13th, 2009 at 12:41 pm

Wow — thank you! Just what I needed. I appreciate your simple approach.

Avatar

styson

August 25th, 2009 at 9:50 am

Avatar

Oleg.K

October 5th, 2009 at 9:10 am

I’m impressed. You’r ninja!

Avatar

Ressol

October 12th, 2009 at 5:20 pm

it’s awesome, thanks for your solution.

Avatar

Tom

October 13th, 2009 at 8:09 am

Actually, with jQuery 1.3.2 this is unecessary.

All you have to do is create your custom sorting function.

function sortAlpha() { … }

$(“ol.tosort li”).sort(sortAlpha).appendTo(“ol.sorted”);

This is because in jQuery-1.3.2, the sort method uses the built in array sort.

@285: sort: [].sort,

Avatar

slade73

October 16th, 2009 at 6:22 am

Thanks! I needed to be able to sort a wrapped set by element ID, and this helped me do it. Will be mentioning this post on my blog, http://slade73.blogspot.com.

Avatar

iskra

December 11th, 2009 at 1:01 am

Works beautifully… unlike most plugin functions I had this thing working in less than 2 seconds!

Avatar

Benny

January 4th, 2010 at 5:20 am

I have been using this for some time now and it works RELY good on my site.
There is one problem. FF have been updater and don’t support this way any more. I have send in a bug to FF development, but it can take forever to be solved.
Have a look at http://www.odinsoft.dk/test/Dropdowntest.html in both FF and IE.
Can there be done a work around on this problem ??

Comment Form

top