Find the min/max element of an Array in JavaScript

前端 未结 30 2061
無奈伤痛
無奈伤痛 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 07:00

    Using Math.max() or Math.min()

    Math.max(10, 20);   //  20
    Math.min(-10, -20); // -20
    

    The following function uses Function.prototype.apply() to find the maximum element in a numeric array. getMaxOfArray([1, 2, 3]) is equivalent to Math.max(1, 2, 3), but you can use getMaxOfArray() on programmatically constructed arrays of any size.

    function getMaxOfArray(numArray) {
      return Math.max.apply(null, numArray);
    }
    

    Or with the new spread operator, getting the maximum of an array becomes a lot easier.

    var arr = [1, 2, 3];
    var max = Math.max(...arr); // 3
    var min = Math.min(...arr); // 1
    

提交回复
热议问题