Javascript 为什么 lodash 不能从数组中找到最大值?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/44614973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:39:17  来源:igfitidea点击:

why can't lodash find the max value from an array?

javascriptlodash

提问by Joey Yi Zhao

I have below code and I tried to use lodashto find the max value from an array object;

我有下面的代码,我试图用来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);

the output is 47.67196715489599which is not the maximum value. What is wrong with my code?

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

回答by Ori Drori

Lodash's _.max()doesn't accept an iteratee (callback). Use _.maxBy()instead:

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>

回答by Maurits Rijk

Or even shorter:

或者更短:

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);

This uses the _.propertyiteratee shorthand.

这使用_.propertyiteratee 速记。