Find the min/max element of an Array in JavaScript

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

    How about augmenting the built-in Array object to use Math.max/Math.min instead:

    Array.prototype.max = function() {
      return Math.max.apply(null, this);
    };
    
    Array.prototype.min = function() {
      return Math.min.apply(null, this);
    };
    

    Here is a JSFiddle.

    Augmenting the built-ins can cause collisions with other libraries (some see), so you may be more comfortable with just apply'ing Math.xxx() to your array directly:

    var min = Math.min.apply(null, arr),
        max = Math.max.apply(null, arr);
    

    Alternately, assuming your browser supports ECMAScript 6, you can use the spread operator which functions similarly to the apply method:

    var min = Math.min( ...arr ),
        max = Math.max( ...arr );
    

提交回复
热议问题