Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 496
Joey Yi Zhao Avatar asked Jun 18 '17 12:06

Joey Yi Zhao


People also ask

How check if array is empty Lodash?

The Lodash _. isEmpty() Method Checks if the value is an empty object, collection, map, or set. Objects are considered empty if they have no own enumerable string keyed properties. Collections are considered empty if they have a 0 length.

What does Lodash find return?

Lodash's find() function returns the first element of a collection that matches the given predicate .

How does Lodash find work?

The _. find() method accessing each value of the collection and returns the first element that passes a truth test for the predicate or undefined if no value passes the test. The function returns as soon as it finds the match.


2 Answers

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>
like image 81
Ori Drori Avatar answered Sep 28 '22 21:09

Ori Drori


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.

like image 25
Maurits Rijk Avatar answered Sep 28 '22 21:09

Maurits Rijk