Find the min/max element of an Array in JavaScript

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

    For big arrays (~10⁷ elements), Math.min and Math.max procuces a RangeError (Maximum call stack size exceeded) in node.js.

    For big arrays, a quick & dirty solution is:

    Array.prototype.min = function() {
        var r = this[0];
        this.forEach(function(v,i,a){if (v

提交回复
热议问题