0

Is it possible to combine a ._max and a pluck?

Finding Max Works and returns an object with the highest scoreLabel

var maxScore = _.max(peopleList, scoreLabel);

But combining it with pluck returns a list of undefined

_.pluck(_.max(peopleList, scoreLabel), scoreLabel);
Joe Frambach
  • 26,300
  • 10
  • 69
  • 98
lost9123193
  • 9,040
  • 22
  • 62
  • 100

2 Answers2

2

The purpose of _.pluck is to retrieve a field for each object in a collection - since _.max returns only a single object, you don't need to pluck, you can simply retrieve the field from the one object you have:

var maxScore = _.max(peopleList, scoreLabel)[scoreLabel];

The above will retrieve the person from peopleList who has the largest scoreLabel, and then retrieve that person's scoreLabel value.

Alternatively, you could swap the order of the calls to _.max and _.pluck, like this:

var maxScore = _.max(_.pluck(peopleList, scoreLabel));

This will build a collection of all the scoreLabel values, and then retrieve the largest one.

00dani
  • 1,478
  • 15
  • 17
1

_.max(peopleList, scoreLabel) returns a person, not a collection of people, so you can simply access its scoreLabel property using bracket notation to get the maxScore.

var maxScore = _.max(peopleList, scoreLabel)[scoreLabel]

It looks like _.pluck has also been deprecated in favor of _.map(list, 'property') for the latest version of Lodash.

Community
  • 1
  • 1
gyre
  • 15,375
  • 3
  • 34
  • 47