简体   繁体   English

使用 underscore.js 从对象数组中获取最小值和最大值

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

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.我需要根据 prop2 找到最小值和最大值,所以这里我的数字是 20 和 78。

How can I write code in Underscore to do that?如何在 Underscore 中编写代码来做到这一点?

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如果你不是 ES6 那种人,那么

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

You can use the _.maxBy to find max value as follows.您可以使用 _.maxBy 来查找最大值,如下所示。

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

or with the iteratee shorthand as follows或使用 iteratee 简写如下

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

similarly the _.minBy as well; _.minBy 也类似;

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

使用 _.max 和 _.property:

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

Use _.max as follows:使用 _.max 如下:

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.使用函数作为第二个输入还允许您访问对象中的嵌套值。

Underscore下划线

use _.sortBy(..) to sort your object by a property使用 _.sortBy(..) 按属性对对象进行排序

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然后你会得到一个通过 prop1 属性排序的数组, sorted[0]是最小值, sorted[n]是最大值

Plain JS纯JS

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM