简体   繁体   中英

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 AZ?

thx

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

返回(在Firebug中):

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

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;

});

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.

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

eg

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM