Find the min/max element of an Array in JavaScript

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

    This may suit your purposes.

    Array.prototype.min = function(comparer) {
    
        if (this.length === 0) return null;
        if (this.length === 1) return this[0];
    
        comparer = (comparer || Math.min);
    
        var v = this[0];
        for (var i = 1; i < this.length; i++) {
            v = comparer(this[i], v);    
        }
    
        return v;
    }
    
    Array.prototype.max = function(comparer) {
    
        if (this.length === 0) return null;
        if (this.length === 1) return this[0];
    
        comparer = (comparer || Math.max);
    
        var v = this[0];
        for (var i = 1; i < this.length; i++) {
            v = comparer(this[i], v);    
        }
    
        return v;
    }
    

提交回复
热议问题