Joey Yi Zhao
Joey Yi Zhao

Reputation: 42556

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

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?

Upvotes: 28

Views: 51375

Answers (2)

Ori Drori
Ori Drori

Reputation: 192287

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>

Upvotes: 65

Maurits Rijk
Maurits Rijk

Reputation: 9985

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.

Upvotes: 14

Related Questions