Find the min/max element of an Array in JavaScript

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

    You can use the following function anywhere in your project:

    function getMin(array){
        return Math.min.apply(Math,array);
    }
    
    function getMax(array){
        return Math.max.apply(Math,array);
    }
    

    And then you can call the functions passing the array:

    var myArray = [1,2,3,4,5,6,7];
    var maximo = getMax(myArray); //return the highest number
    

提交回复
热议问题