Get the largest and smallest number in the array

JS filter the largest number in the array
ES5
Math.max.apply(null, [1, 2, 3, 4, 5]) // 5
ES6
Math.max(...[1, 2, 3, 4, 5]) // 5
JS filter the smallest number in the array
ES5
Math.min.apply(null, [1, 2, 3, 4, 5]) // 1
ES6
Math.min(...[1, 2, 3, 4, 5]) // 1

注意: 数组的每一项要是数字类型且不为NaN, 一般项目中数组不会是每一项的纯数字, 要先对数组进行转化

例子:

let tempArray = [
  {
    
    
    a: 'xxx'
    b: '123'
  },
  {
    
    
    a: 'xxx'
    b: '非数字类型'
  },
  ...
]
let filterArr = tempArray.map(item => +item.b).filter(item => item === item)
let maxNumber = Math.max(...filterArr)

此示例中 +item.b 转化为数字的过程中, 没有考虑, 空字符串'', 空数组[], 等一些特殊字符会转化为0的情况, 根据具体项目情况具体处理

Guess you like

Origin blog.csdn.net/zty867097449/article/details/115129403