Find the min/max element of an Array in JavaScript

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

    For big arrays (~10⁷ elements), Math.min and Math.max both produces the following error in Node.js.

    RangeError: Maximum call stack size exceeded

    A more robust solution is to not add every element to the call stack, but to instead pass an array:

    function arrayMin(arr) {
      return arr.reduce(function (p, v) {
        return ( p < v ? p : v );
      });
    }
    
    function arrayMax(arr) {
      return arr.reduce(function (p, v) {
        return ( p > v ? p : v );
      });
    }
    

    If you are concerned about speed, the following code is ~3 times faster then Math.max.apply is on my computer. See http://jsperf.com/min-and-max-in-array/2.

    function arrayMin(arr) {
      var len = arr.length, min = Infinity;
      while (len--) {
        if (arr[len] < min) {
          min = arr[len];
        }
      }
      return min;
    };
    
    function arrayMax(arr) {
      var len = arr.length, max = -Infinity;
      while (len--) {
        if (arr[len] > max) {
          max = arr[len];
        }
      }
      return max;
    };
    

    If your arrays contains strings instead of numbers, you also need to coerce them into numbers. The below code does that, but it slows the code down ~10 times on my machine. See http://jsperf.com/min-and-max-in-array/3.

    function arrayMin(arr) {
      var len = arr.length, min = Infinity;
      while (len--) {
        if (Number(arr[len]) < min) {
          min = Number(arr[len]);
        }
      }
      return min;
    };
    
    function arrayMax(arr) {
      var len = arr.length, max = -Infinity;
      while (len--) {
        if (Number(arr[len]) > max) {
          max = Number(arr[len]);
        }
      }
      return max;
    };
    

提交回复
热议问题