Find the min/max element of an Array in JavaScript

前端 未结 30 2052
無奈伤痛
無奈伤痛 2020-11-21 06:18

How can I easily obtain the min or max element of a JavaScript Array?

Example Psuedocode:

let array = [100, 0, 50]

array.min() //=> 0
array.max()         


        
30条回答
  •  挽巷
    挽巷 (楼主)
    2020-11-21 06:39

    Two ways are shorter and easy:

    let arr = [2, 6, 1, 0]
    

    Way 1:

    let max = Math.max.apply(null, arr)
    

    Way 2:

    let max = arr.reduce(function(a, b) {
        return Math.max(a, b);
    });
    

提交回复
热议问题