JQuery sort()
11
Feb
2009

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()
Martijn Laarman
May 8th, 2009 at 7:16 am
Good job on a lean solution, jquery really needs a sort method like this one
mclemmens
August 13th, 2009 at 12:41 pm
Wow — thank you! Just what I needed. I appreciate your simple approach.
styson
August 25th, 2009 at 9:50 am
Thanks for the post. It helped me get a task done today. http://blogs.dovetailsoftware.com/blogs/styson/archive/2009/08/25/using-jquery-to-sort-a-list.aspx
Oleg.K
October 5th, 2009 at 9:10 am
I’m impressed. You’r ninja!
Ressol
October 12th, 2009 at 5:20 pm
it’s awesome, thanks for your solution.
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,
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.
iskra
December 11th, 2009 at 1:01 am
Works beautifully… unlike most plugin functions I had this thing working in less than 2 seconds!
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 ??