取出最小值有没有简单的方法?

只取那个height字段的最大值 我能想到的方法就是下面这样的 不知道有没有更简单的?我想在循环时就取出最大值能做到吗?

var arr=[]
data.map((res)=>{
   return arr.push(res.height)
})
var max = Math.max.apply(null, arr)
console.log(max)
var data=[
        {
            user: 'aaa',
            height: 62
        },
        {
            user: 'bbb',
            height: 316
        },
        {
            user: 'ccc',
            height: 128
        },
        {
            user: 'ddd',
            height: 920
        },
        {
            user: 'eee',
            height: 262
        },
]
阅读 2.4k
4 个回答
var max = 0;
data.forEach((v =>{
    if(v.height >= max) {
         max = v.height;
    }
})

lodash.maxby解忧愁

_.maxBy(objects, item => item.height).height

原生的话

Math.max.apply(null, data.map(item => item.height))
function demo (arr) {
  return arr.reduce((max, item) => Math.max(max, item.height), 0)
}


var res = demo([
  {
    user: 'aaa',
    height: 62
  },
  {
    user: 'bbb',
    height: 316
  },
  {
    user: 'ccc',
    height: 128
  },
  {
    user: 'ddd',
    height: 920
  },
  {
    user: 'eee',
    height: 262
  },
  {
    user: 'fff',
    height: 920
  },
])


console.log(res) // => 920

这个没什么难度吧

let result = data.reduce((res, item) => res && item.height < res.height ? res : item, null)

result:

{user: "ddd", height: 920}

一次循环可得结果。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题