I have searched and tried hard to achieve this but completely stuck and hoping somebody on here can help. Basically I would like to be able to click on a button and use jQuery to sort an unordered list alphabetically by group heading and then each nested list alphabetically within each group. Many thanks in advance and here goes...
The default list:
<ul id="list">
<li><a href="#" rel="Meat">Lamb</a></li>
<li><a href="#" rel="Meat">Pork</a></li>
<li><a href="#" rel="Meat">Beef</a></li>
<li><a href="#" rel="Fruit and Vegetables">Banana</a></li>
<li><a href="#" rel="Fruit and Vegetables">Orange</a></li>
<li><a href="#" rel="Fruit and Vegetables">Cabbage</a></li>
</ul>
Click a button and then sort the list to something like this:
<ul id="list">
<li class="grouphead">Fruit and Vegetables</li>
<ul>
<li><a href="#" rel="Fruit and Vegetables">Banana</a></li>
<li><a href="#" rel="Fruit and Vegetables">Cabbage</a></li>
<li><a href="#" rel="Fruit and Vegetables">Orange</a></li>
</ul>
<li class="grouphead">Meat</li>
<ul>
<li><a href="#" rel="Meat">Beef</a></li>
<li><a href="#" rel="Meat">Lamb</a></li>
<li><a href="#" rel="Meat">Pork</a></li>
</ul>
</ul><!-- End: #list -->
var dict = {
}
//read items from list
$("#list li").each( function() {
var k = $(this).children(":first").attr('rel');
if ( dict.hasOwnProperty(k) == false ) {
dict[k] = [];
}
dict[k].push( $(this).html() );
} );
//clear old list items
$("#list").empty();
function newList(nam) {
var r = "";
for ( c in dict[nam] ) {
r += "<li>" + dict[nam][c] + "</li>";
}
return r;
}
//create new list
for ( nam in dict ) {
$("#list").append("<li class='grouphead'>" + nam + "</li>");
$("#list").append("<ul>" + newList(nam) + "</ul>");
}
http://jsfiddle.net/r5QQT/7/
I modified your HTML a little bit to make selection simpler in this answer:
<ul id="list">
<li><a href="#" rel="Meat">Lamb</a></li>
<li><a href="#" rel="Meat">Pork</a></li>
<li><a href="#" rel="Meat">Beef</a></li>
<li><a href="#" rel="Fruit and Vegetables">Banana</a></li>
<li><a href="#" rel="Fruit and Vegetables">Orange</a></li>
<li><a href="#" rel="Fruit and Vegetables">Cabbage</a></li>
</ul>
<ul id="newone">
<li class="grouphead">Fruit and Vegetables</li>
<ul id="Fruit">
</ul>
<li class="grouphead">Meat</li>
<ul id="Meat">
</ul>
</ul>
var dict = {
"Meat" : [],
"Fruit and Vegetables" : []
}
$("#list li").each( function() {
dict[$(this).children(":first").attr('rel')].push( $(this).html() );
} );
$.each( dict["Meat"], function(k, v) {
$("#Meat").append( "<li>" + v + "</li>" );
});
$.each( dict["Fruit and Vegetables"], function(k, v) {
$("#Fruit").append( "<li>" + v + "</li>" );
});
Here is it in a Fiddle: http://jsfiddle.net/r5QQT/1/