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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/33351934/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 16:24:06  来源:igfitidea点击:

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

javascriptarraysunderscore.js

提问by sarsnake

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 中编写代码来做到这一点?

回答by

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

回答by Meir

use _.max and _.property:

使用 _.max 和 _.property:

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

回答by Nadeeshaan

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

回答by ykay says Reinstate Monica

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.

使用函数作为第二个输入还允许您访问对象中的嵌套值。

回答by svarog

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