简体   繁体   English

JQUERY对对象数组进行排序

[英]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对象如下所示-每个对象一次添加一次:

 <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? 有没有一种快速的方法可以根据AZ的ID对数组中的DIV对象进行排序?

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. 由于仅在浪费资源的情况下,就提出了许多愚蠢的实现都在使用jQuery,因此我将提出自己的建议。 This is just a straight javascript sort of an array by a property of the object in the array. 通过数组中对象的属性,这只是对数组的一种简单的javascript排序。 To do that you just use the array sort method with a custom comparison function that does an alpha comparison of the id value. 为此,您只需将数组排序方法与自定义比较函数一起使用,该函数将对id值进行alpha比较。 There is no reason or advantage to involve jQuery in this at all. 完全没有理由或优势让jQuery参与其中。

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. 请注意,按照问题的要求,它将对数组中的div引用列表进行排序。 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. 为此,您必须对引用列表进行排序,然后根据新的数组顺序重新排列页面中的div。

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: 如果您可以依靠自己的HTML中没有两个ID完全相同的事实(因为您永远都不应该拥有两个具有相同ID的对象),则可以缩短并加快自定义排序功能,使其成为:

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) 您可以使用tinysort插件)(http://plugins.jquery.com/project/TinySort)

eg 例如

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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