Sort Array by attribute

前端 未结 3 1945
太阳男子
太阳男子 2020-12-24 10:31

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

    { champions.slice(0,3).map(function(ch
相关标签:
3条回答
  • 2020-12-24 10:58

    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(...
    
    0 讨论(0)
  • 2020-12-24 11:06

    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) {
    
    0 讨论(0)
  • 2020-12-24 11:16

    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.

    0 讨论(0)
提交回复
热议问题