Why can't lodash find the maximum value from an array?

I have the code below and I tried to use lodashto find the maximum 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);

output 47.67196715489599that is not a maximum value. What is wrong with my code?

+6
source share
2 answers

Lodash _.max()does not accept iteration (callback). Use instead _.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>
Run codeHide result
+13
source

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

It uses the abbreviated _.propertyiteratee.

+2
source

All Articles