Get the min and max from array of objects with underscore.js

て烟熏妆下的殇ゞ 提交于 2019-12-10 06:59: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.

How can I write code in Underscore to do 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:


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:


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:


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;
})


来源:https://stackoverflow.com/questions/33351934/get-the-min-and-max-from-array-of-objects-with-underscore-js

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!