【问题标题】:why can't lodash find the max value from an array?为什么 lodash 不能从数组中找到最大值?
【发布时间】:2017-06-18 12:28:58
【问题描述】:

我有以下代码,我尝试使用lodash 从数组对象中查找最大值;

var a = [ { type: 'exam', score: 47.67196715489599 },
  { type: 'quiz', score: 41.55743490493954 },
  { type: 'homework', score: 70.4612811769744 },
  { type: 'homework', score: 48.60803337116214 } ];
 var _ = require("lodash")

 var b = _.max(a, function(o){return o.score;})
 console.log(b);

输出是47.67196715489599,这不是最大值。我的代码有什么问题?

【问题讨论】:

    标签: javascript lodash


    【解决方案1】:

    Lodash 的 _.max() 不接受迭代(回调)。请改用_.maxBy():

    var a = [{"type":"exam","score":47.67196715489599},{"type":"quiz","score":41.55743490493954},{"type":"homework","score":70.4612811769744},{"type":"homework","score":48.60803337116214}];
    
    
    console.log(_.maxBy(a, function(o) {
      return o.score;
    }));
    
    // or using `_.property` iteratee shorthand
    
    console.log(_.maxBy(a, 'score'));
    <script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.min.js"></script>

    【讨论】:

      【解决方案2】:

      甚至更短:

      var a = [{"type":"exam","score":47.67196715489599},{"type":"quiz","score":41.55743490493954},{"type":"homework","score":70.4612811769744},{"type":"homework","score":48.60803337116214}];
      
      const b = _.maxBy(a, 'score');
      console.log(b);
      

      这使用_.property iteratee 简写。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-30
        • 1970-01-01
        • 1970-01-01
        • 2020-02-24
        • 2014-12-12
        • 2023-03-16
        • 1970-01-01
        • 2014-10-23
        相关资源
        最近更新 更多