JQUERY Sorting an Array of Objects

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

Answers:

Answer

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;
});
Answer
$('.chatmember').sort(function(a,b){ return a.id > b.id; })...

Returns (in Firebug):

[div#adam.chatmember, div#bob.chatmember, div#mary.chatmember, div#peter.chatmember, div#steven.chatmember]
Answer

Try this:

activeMembers.sort(function(a,b){
   var aid = $(a).attr('id');
   var bid = $(b).attr('id');

   return (aid==bid) ? 0 : (aid > bid) ? 1 : -1;

});
Answer

There is no quick way. You can use generic sorter that allow you to provide comparator, or you can write a custom sorter.

See here for an example.

Answer

You can use the tinysort plugin )(http://plugins.jquery.com/project/TinySort)

e.g.

$("#parentName > div").tsort("",{attr:"id"});

Tags

Recent Questions

Top Questions

Home Tags Terms of Service Privacy Policy DMCA Contact Us Javascript

©2020 All rights reserved.