Get the min and max from array of objects with und

2019-05-09 09:05发布

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?

5条回答
走好不送
2楼-- · 2019-05-09 09:14

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 });
查看更多
疯言疯语
3楼-- · 2019-05-09 09:18

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

查看更多
贪生不怕死
4楼-- · 2019-05-09 09:26

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.

查看更多
5楼-- · 2019-05-09 09:33

use _.max and _.property:

var max value = _.max(myArrofObjects, _.property('prop2'));
查看更多
放我归山
6楼-- · 2019-05-09 09:41

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;
})
查看更多
登录 后发表回答