Monday, June 3, 2024
 Popular · Latest · Hot · Upcoming
110
rated 0 times [  117] [ 7]  / answers: 1 / hits: 20047  / 13 Years ago, thu, august 18, 2011, 12:00:00

I have an array that is holding a number of objects.



Array:



 var activeMembers=[];


The DIV objects in the above array look like as follows - each was added one at a time:



 <div id=mary class=chatmember 1011></div>
<div id=steven class=chatmember 1051></div>
<div id=adam class=chatmember 1701></div>
<div id=bob class=chatmember 1099></div>
<div id=peter class=chatmember 1123></div>


Is there a quick way to sort theses DIV objects in the array by the ID from A-Z?



thx


More From » jquery

 Answers
2

Since there are so many silly implementations being proposed that are using jQuery when it is only a waste of resources, I'll propose my own. This is just a straight javascript sort of an array by a property of the object in the array. To do that you just use the array sort method with a custom comparison function that does an alpha comparison of the id value. There is no reason or advantage to involve jQuery in this at all.



activeMembers.sort(function(a, b) {
var aID = a.id;
var bID = b.id;
return (aID == bID) ? 0 : (aID > bID) ? 1 : -1;
});


Note, as requested in the question, this sorts a list of div references in the array. It does not sort the objects in the layout of the page. To do that, you'd have to sort the references list, then rearrange the divs in the page according to the new array order.



If you can rely on the fact that no two IDs are ever the same in your own HTML (since you are never supposed to have two objects with the same ID), you can shorten and speed up the custom sort function to just be this:



activeMembers.sort(function(a, b) {
return (a.id > b.id) ? 1 : -1;
});

[#90554] Tuesday, August 16, 2011, 13 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
freddiej

Total Points: 294
Total Questions: 95
Total Answers: 97

Location: Saudi Arabia
Member since Sat, Aug 20, 2022
2 Years ago
;