对对象数组进行排序
我有一个像这样的对象文字数组:
var myArr = [];
myArr[0] = {
'score': 4,
'name': 'foo'
}
myArr[1] = {
'score': 1,
'name': 'bar'
}
myArr[2] = {
'score': 3,
'name': 'foobar'
}
我如何对数组进行排序,以便它按“分数”参数升序,这样它就会更改为:
myArr[0] = {
'score': 1,
'name': 'bar'
}
myArr[1] = {
'score': 3,
'name': 'foobar'
}
myArr[2] = {
'score': 4,
'name': 'foo'
}
提前致谢。
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'
}
Thanks in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
尝试 myArr.sort(function (a, b) {return a.score - b.score});
数组元素的排序方式取决于传入的函数返回的数字:
< 0
(负数):a
领先于b
> 0
(正数):b
领先于a
0
:在这种情况下,两个数字在排序中将相邻列表。但是,排序并不能保证稳定:a
和b
相对于彼此的顺序可能发生变化。Try
myArr.sort(function (a, b) {return a.score - b.score});
The way the array elements are sorted depends on what number the function passed in returns:
< 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.您可以查看 MDN 上的 Array.sort 文档 。特别是关于提供自定义compareFunction的文档
You could have a look at the Array.sort documentation on MDN. Specifically at the documentation about providing a custom compareFunction
lodash 排序
lodash sortBy