I right now just get the first 3 Object of an Array and map over them:
{
champions.slice(0,3).map(function(ch
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(...
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) {
The pure JS solutions are nice. But if your project is set up via npm, you can also use Lodash or Underscore. In many cases those are already sub-dependencies so no extra weight is incurred.
Combining ES6 and _.orderBy
provided by lodash
_.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.