Friday, May 17, 2024
 Popular · Latest · Hot · Upcoming
114
rated 0 times [  117] [ 3]  / answers: 1 / hits: 17304  / 13 Years ago, wed, july 6, 2011, 12:00:00

My question is very similar to a number of others I've found on Stack Overflow, but not quite the same.



I'd like to sort list items based on the content of a span contained within each item -- but using a sort order that I can define. Here's the HTML for a sample list item:



<li>
<span class=fname>John</span>
<span class=lname>Doe</span>
<span class=year>Sophomore</span>
</li>


I want to sort based on the content of the year span, but chronologically rather than alphabetically. The order, obviously, needs to be:




  • Freshman

  • Sophomore

  • Junior

  • Senior



How can I do this?



Just for reference, I'm using the following jQuery code (which works perfectly) to sort alphabetically by last name:



function sortByLastName(){
var myList = $('#foo ul');
var listItems = myList.children('li').get();
listItems.sort(function(a,b){
var compA = $(a).find('.lname').text().toUpperCase();
var compB = $(b).find('.lname').text().toUpperCase();
return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
});
$(myList).append(listItems);
};

More From » jquery

 Answers
6

To match your sortByLastName() function, this would work:



function sortByYear(){
var myYears = ['Freshman', 'Sophomore', 'Junior', 'Senior'];
var myList = $('#foo ul');
var listItems = myList.children('li').get();
listItems.sort(function(a,b){
var compA = $.inArray($(a).find('.year').text(), myYears);
var compB = $.inArray($(b).find('.year').text(), myYears);
return (compA < compB) ? -1 : (compA > compB) ? 1 : 0;
});
$(myList).append(listItems);
}


Just use $.inArray() to find the indices of each school year within the array. Note that this will return -1 for values not found in the array, which will put those elements at the top of your list.


[#91338] Monday, July 4, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
maryann

Total Points: 600
Total Questions: 104
Total Answers: 97

Location: Sint Maarten
Member since Tue, Mar 29, 2022
2 Years ago
;