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?
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.
Lodash's find() function returns the first element of a collection that matches the given predicate .
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With