使用underscore.js从对象数组中获取min和max [英] Get the min and max from array of objects with underscore.js

查看:317
本文介绍了使用underscore.js从对象数组中获取min和max的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有以下结构

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

我需要根据prop2找到最小值和最大值,所以这里我的数字是20和78 。

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?

推荐答案

你真的不需要像这样的下划线。

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

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

如果你不是ES6那种人,那么

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.

如果您打算同时查找max和min,那么

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

这篇关于使用underscore.js从对象数组中获取min和max的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆