【问题标题】:Javascript: Find maximum value of object property in array in object in array :DJavascript:在数组中的对象中查找数组中对象属性的最大值:D
【发布时间】:2018-06-15 19:00:02
【问题描述】:

我有以下对象数组,我想找到任何人在任何年份的最大体重(体重就足够了,我不需要对应的年份或名称)。

提前谢谢:)

var arr = [
    {
        'name': 'Bob',
        'weights': [
            {
                'weight': 90,
                'year': 2018
            },
            {
                'weight': 85,
                'year': 2017
            },
            // etc.
        ]
    },
        'name': 'Charlie',
        'weights': [
            {
                'weight': 65,
                'year': 2018
            },
            {
                'weight': 60,
                'year': 2017
            },
            // etc.
        ]
    },
    // etc.
]

【问题讨论】:

    标签: javascript jquery arrays object


    【解决方案1】:

    您可以使用Math.max 和展开语法来查找最大值,但您还需要先使用map 来获取一个数组中的权重值。

    var arr = [{"name":"Bob","weights":[{"weight":90,"year":2018},{"weight":85,"year":2017}]},{"name":"Charlie","weights":[{"weight":65,"year":2018},{"weight":60,"year":2017}]}]
    
    var max = Math.max(...[].concat(...arr.map(({weights}) => weights.map(({weight}) => weight))))
    console.log(max)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-07-08
      • 2014-05-07
      • 1970-01-01
      • 1970-01-01
      • 2018-07-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多