Javascript 按属性对数组排序
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28853686/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Sort Array by attribute
提问by Mini John
I right now just get the first 3 Object of an Array and map over them:
我现在只获取数组的前 3 个对象并映射它们:
<ul className="ItemSearchList">
{
champions.slice(0,3).map(function(champ){
return (
<li key={champ.id} >
<div className="media">
<div className="media-left">
<a href="#">
<img className="media-object" src={"http://ddragon.leagueoflegends.com/cdn/5.2.1/img/champion/" + champ.key + ".png"} />
</a>
</div>
<div className="media-body" >
<h4 className="media-heading">{champ.name}</h4>
<div>
something
</div>
</div>
</div>
</li>
)
})
}
</ul>
Each champhas a levelattribute (champ.level).
每个champ都有一个level属性(champ.level)。
How can I sort my output to champ.leveldescendingand slice the first 3?
如何将我的输出排序champ.leveldescending并切片前 3 个?
回答by Jonny Buchanan
Use Array.prototype.sort()with a custom compare function to do the descending sort first:
使用Array.prototype.sort()自定义比较函数首先进行降序排序:
champions.sort(function(a, b) { return b.level - a.level }).slice(...
Even nicer with ES6:
使用 ES6 更好:
champions.sort((a, b) => b.level - a.level).slice(...
回答by Jordi Castilla
Write your own comparison function:
编写自己的比较函数:
function compare(a,b) {
if (a.level < b.level)
return -1;
if (a.level > b.level)
return 1;
return 0;
}
To use it:
要使用它:
champions.sort(compare).slice(0,3).map(function(champ) {
回答by pscl
The pure JS solutions are nice. But if your project is set up via npm, you can also use Lodashor Underscore. In many cases those are already sub-dependencies so no extra weight is incurred.
纯 JS 解决方案很好。但是,如果你的项目是通过NPM设置,您还可以使用Lodash或下划线。在许多情况下,这些已经是子依赖项,因此不会产生额外的重量。
Combining ES6 and _.orderByprovided by lodash
结合 ES6 和_.orderBylodash 提供
_.orderBy(champions, [c => c.level], ['desc']).slice(0,3)
This is a powerful little utility. You can provide multiple tie-breaking sort keys to orderBy, and specify an order for each individually.
这是一个强大的小工具。您可以为 提供多个打破平局的排序键orderBy,并为每个键单独指定一个顺序。

