Reputation: 15
I would like to sort list elements based on its group.
For example:
This:
Will become:
Alphabetically, the group items of Fruit is sorted first, then Sweets.
I am not too sure how to make it so that both sort is correct. For example, I tried sorting the groups then the food items but the group will not be sorted.
function sorting() {
function sortASC(a, b) {
return $(b).find(".group").text() < $(a).find(".group").text();
}
$("li").sort(sortASC).appendTo('ul');
}
Upvotes: 0
Views: 727
Reputation: 7328
You can build it all into one sort function:
function sortASC(a, b) {
// Cache Text
var a_group = $(a).find(".group").text(),
a_item = $(a).find(".item").text(),
b_group = $(b).find(".group").text(),
b_item = $(b).find(".item").text()
return (
b_group < a_group // If group is bigger
|| ( // OR
b_group == a_group // If groups are same
&& b_item < a_item // AND item is bigger
)
);
}
Upvotes: 1