Javascript:如何按其中一个字段中的值对记录数组进行排序?
假设我有一个记录数组:[{a:0,b:0},{a:2,b:1},{a:1,b:2}]
我希望按每个记录中的 a
字段的降序排序,并将排序后的记录作为新数组进行提醒(即新数组将是 [{a:2,b: 1},{a:1,b:2},{a:0,b:0}]
) - 我该怎么做?我尝试了几种方法,但我的头撞在墙上。
谢谢
Possible Duplicate:
Sorting objects in an array by a field value in JavaScript
Suppose I have an array of records: [{a:0,b:0},{a:2,b:1},{a:1,b:2}]
which I wish to sort in descending order of the a
field in each record, and alert the sorted records as a new array (ie the new array would be [{a:2,b:1},{a:1,b:2},{a:0,b:0}]
) - how would I go about this? I've tried a few approaches but am banging my head against the wall.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
一种简单的方法
EDIT
和一种更灵活的方法
EDIT 2
也适用于字符串的版本
A straightforward approach
EDIT
And a more flexible approach
EDIT 2
A version that works for strings as well
排序委托怎么样?
(保存后,我注意到另外两个几乎相同的答案,但我将把我的答案留在这里,以了解细微的差别。)
How about a sort delegate?
(After saving, I noticed two other almost identical answers, but I'll leave mine here for the minor differences.)
使用闭包比直接引用函数慢。
如果您确实需要新数组的第二个变量,只需在调用自定义排序方法之前复制初始数组即可。
Using closures is slower than directly referencing a function.
If you really need a second variable for the new array, simply make a copy of the initial array prior to calling the custom sort method.
结果:[{a:0,b:0},{a:2,b:1},{a:1,b:2}]
结果:[{a:2 ,b:1},{a:1,b:2},{a:0,b:0}]
RESULT: [{a:0,b:0},{a:2,b:1},{a:1,b:2}]
RESULT: [{a:2,b:1},{a:1,b:2},{a:0,b:0}]
我的同事休斯今天刚刚向我展示了以下内容。
请注意使用 -cmp() 和 cmp() 进行降序和升序。
Hughes my colleague just showed me today the following.
Note the use of -cmp() and cmp() for descending and ascending.