Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort Array by attribute

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?

like image 361
Mini John Avatar asked Mar 04 '15 11:03

Mini John


Video Answer


1 Answers

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(... 
like image 172
Jonny Buchanan Avatar answered Oct 01 '22 20:10

Jonny Buchanan