JQUERY对一组对象进行排序 [英] JQUERY Sorting an Array of Objects

查看:87
本文介绍了JQUERY对一组对象进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个对象的数组。

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

数组:

 var activeMembers=[];

上述数组中的DIV对象如下所示 - 每次添加一个:

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>

有没有一种快速方法可以通过AZ中的ID对数组中的DIV对象进行排序?

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

thx

推荐答案

由于提出了很多愚蠢的实施,使用jQuery时只是浪费资源,我会提出自己的。这只是数组中对象属性的直接javascript排序数组。为此,您只需将数组排序方法与自定义比较函数一起使用,该函数对id值进行alpha比较。根本没有理由或优势让jQuery参与其中。

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;
});

注意,根据问题的要求,这会对数组中的div引用列表进行排序。它不会对页面布局中的对象进行排序。要做到这一点,你必须对引用列表进行排序,然后根据新的数组顺序重新排列页面中的div。

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.

如果你可以依赖这个事实在你自己的HTML中没有两个ID是相同的(因为你永远不应该有两个具有相同ID的对象),你可以缩短和加速自定义排序功能就是这样:

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;
});

这篇关于JQUERY对一组对象进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆