How may I sort a list alphabetically using jQuery?

dougoftheabaci picture dougoftheabaci · Jul 16, 2009 · Viewed 297k times · Source

I'm a bit out of my depth here and I'm hoping this is actually possible.

I'd like to be able to call a function that would sort all the items in my list alphabetically.

I've been looking through the jQuery UI for sorting but that doesn't seem to be it. Any thoughts?

Answer

SolutionYogi picture SolutionYogi · Jul 16, 2009

Something like this:

var mylist = $('#myUL');
var listitems = mylist.children('li').get();
listitems.sort(function(a, b) {
   return $(a).text().toUpperCase().localeCompare($(b).text().toUpperCase());
})
$.each(listitems, function(idx, itm) { mylist.append(itm); });

From this page: http://www.onemoretake.com/2009/02/25/sorting-elements-with-jquery/

Above code will sort your unordered list with id 'myUL'.

OR you can use a plugin like TinySort. https://github.com/Sjeiti/TinySort