查找对象数组中某属性的最大最小值的快捷方法

例如要查找array数组中对象的value属性的最大值

var array=[
        {
            "index_id": 119,
            "area_id": "18335623",
            "name": "满意度",
            "value": "100"
        },
        {
            "index_id": 119,
            "area_id": "18335624",
            "name": "满意度",
            "value": "20"
        },
        {
            "index_id": 119,
            "area_id": "18335625",
            "name": "满意度",
            "value": "80"
        }];
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20

一行代码搞定

Math.max.apply(Math, array.map(function(o) {return o.value}))
  • 1

执行以上一行代码可返还所要查询的array数组中对象value属性的最大值100。 
同理,要查找最小值如下即可:

Math.min.apply(Math, array.map(function(o) {return o.value}))
  • 1

是不是比for循环方便了很多。

posted on 2018-08-09 15:18  斧子兔  阅读(293)  评论(0编辑  收藏  举报