Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
52
rated 0 times [  59] [ 7]  / answers: 1 / hits: 65985  / 9 Years ago, wed, march 4, 2015, 12:00:00

I right now just get the first 3 Object of an Array and map over them:



<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 champ has a level attribute (champ.level).



How can I sort my output to champ.level descending and slice the first 3?


More From » reactjs

 Answers
52

Use Array.prototype.sort() with a custom compare function to do the descending sort first:



champions.sort(function(a, b) { return b.level - a.level }).slice(...


Even nicer with ES6:



champions.sort((a, b) => b.level - a.level).slice(...

[#67579] Sunday, March 1, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
monetm

Total Points: 615
Total Questions: 103
Total Answers: 119

Location: Finland
Member since Fri, Oct 21, 2022
2 Years ago
monetm questions
Fri, Feb 26, 21, 00:00, 3 Years ago
Wed, Sep 9, 20, 00:00, 4 Years ago
Sun, Jul 26, 20, 00:00, 4 Years ago
Thu, Jun 11, 20, 00:00, 4 Years ago
;