js获取数组对象中某个属性的最大值或最小值

80 阅读1分钟
list: [

    { id: 1, name: 'jack' },

    { id: 2, name: 'may' },

    { id: 3, name: 'shawn' },

    { id: 4, name: 'tony' },

    ]

1、Math方法

// 最大值 4
Math.max.apply(Math,this.list.map(item => { return item.id }))

// 最小值 1
 Math.min.apply(Math,this.list.map(item => { return item.id }))

2、sort排序

需要注意的是,sort()对数组排序,不开辟新的内存,对原有数组元素进行调换, 所以这种操作会使得原来的数组元素的位置发生变化

// 最大值 4
this.list.sort((a, b) => { return b-a })[0].id  
 
// 最小值 1
this.list.sort((a, b) => { return a-b })[0].id