对象数组排序 [英] Sort array of objects
本文介绍了对象数组排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有对象文本的这样一个数组:
I have an array of object literals like this:
var myArr = [];
myArr[0] = {
'score': 4,
'name': 'foo'
}
myArr[1] = {
'score': 1,
'name': 'bar'
}
myArr[2] = {
'score': 3,
'name': 'foobar'
}
我将如何排序的数组,因此上升的'分数'等参数,这将改变为:
How would I sort the array so it ascends by the 'score' parameter such that it would change to:
myArr[0] = {
'score': 1,
'name': 'bar'
}
myArr[1] = {
'score': 3,
'name': 'foobar'
}
myArr[2] = {
'score': 4,
'name': 'foo'
}
先谢谢了。
推荐答案
尝试 myArr.sort(功能(A,B){返回a.score - b.score});
数组元素进行排序的方式取决于什么号码的回报传递的函数:
The way the array elements are sorted depends on what number the function passed in returns:
-
< 0
(负数):A
向前走乙
-
> 0
(正数):B
去提前A
-
0
:在此情况下,两个数字将在排序的列表相邻。然而,排序不能保证稳定:顺序A
和B
彼此相对的可能的变化。
< 0
(negative number):a
goes ahead ofb
> 0
(positive number):b
goes ahead ofa
0
: In this cases the two numbers will be adjacent in the sorted list. However, the sort is not guaranteed to be stable: the order ofa
andb
relative to each other may change.
这篇关于对象数组排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文