I have below code and I tried to use lodash
to find the max value from an array object;
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.67196715489599
which is not the maximum value. What is wrong with my code?
Lodash's _.max()
doesn't accept an iteratee (callback). Use _.maxBy()
instead:
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>
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 _.property
iteratee shorthand.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.