我有以下代码,我尝试使用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
,这不是最大值。我的代码出了什么问题?
答案 0 :(得分:28)
Lodash的_.max()
不接受迭代(回调)。请改用_.maxBy()
:
getSupportActionBar().setHomeButtonEnabled(true);

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

答案 1 :(得分:4)
甚至更短:
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简写。