Find the min/max element of an Array in JavaScript

前端 未结 30 2056
無奈伤痛
無奈伤痛 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:47

    I am surprised not one mentiond the reduce function.

    var arr = [1, 10, 5, 11, 2]
    
    var b = arr.reduce(function(previous,current){ 
                          return previous > current ? previous:current
                       });
    
    b => 11
    arr => [1, 10, 5, 11, 2]
    

提交回复
热议问题