Find the min/max element of an Array in JavaScript

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

    If you're paranoid like me about using Math.max.apply (which could cause errors when given large arrays according to MDN), try this:

    function arrayMax(array) {
      return array.reduce(function(a, b) {
        return Math.max(a, b);
      });
    }
    
    function arrayMin(array) {
      return array.reduce(function(a, b) {
        return Math.min(a, b);
      });
    }
    

    Or, in ES6:

    function arrayMax(array) {
      return array.reduce((a, b) => Math.max(a, b));
    }
    
    function arrayMin(array) {
      return array.reduce((a, b) => Math.min(a, b));
    }
    

    The anonymous functions are unfortunately necessary (instead of using Math.max.bind(Math) because reduce doesn't just pass a and b to its function, but also i and a reference to the array itself, so we have to ensure we don't try to call max on those as well.

提交回复
热议问题