Get the min and max from array of objects with und

2019-05-09 08:53发布

问题:

Let's say I have the following structure

var myArrofObjects =  [
    {prop1:"10", prop2:"20", prop3: "somevalue1"},
    {prop1:"11", prop2:"26", prop3: "somevalue2"},
    {prop1:"67", prop2:"78", prop3: "somevalue3"} ];

I need to find the min and max based on prop2, so here my numbers would be 20 and 78.

Can you please help me with writing out the underscore way of doing that?

回答1:

You don't really need underscore for something like this.

Math.max(...arrayOfObjects.map(elt => elt.prop2));

If you're not an ES6 kind of guy, then

Math.max.apply(0, arrayOfObjects.map(function(elt) { return elt.prop2; }));

Use the same approach for minimum.

If you're intent on finding max and min at the same time, then

arrayOfObjects . 
  map(function(elt) { return elt.prop2; }) .
  reduce(function(result, elt) {
    if (elt > result.max) result.max = elt;
    if (elt < result.min) result.min = elt;
    return result;
  }, { max: -Infinity, min: +Infinity });


回答2:

use _.max and _.property:

var max value = _.max(myArrofObjects, _.property('prop2'));


回答3:

Use _.max as follows:

var max_object = _.max(myArrofObjects, function(object){return object.prop2})

Using a function as the second input will allow you to access nested values in the object as well.



回答4:

You can use the _.maxBy to find max value as follows.

var maxValObject = _.maxBy(myArrofObjects, function(o) { return o.prop2; });

or with the iteratee shorthand as follows

var maxValObject = _.maxBy(myArrofObjects, 'prop2');

similarly the _.minBy as well;

Ref: https://lodash.com/docs/4.17.4#maxBy



回答5:

Underscore

use _.sortBy(..) to sort your object by a property

var sorted = _.sortBy(myArrofObjects, function(item){
    return item.prop2;
});

you will then get a sorted array by your prop1 property, sorted[0] is the min, and sorted[n] is the max

Plain JS

myArrofObjects.sort(function(a, b) {
    return a.prop2 - b.prop2;
})