Find the min/max element of an Array in JavaScript

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

    .apply is often used when the intention is to invoke a variadic function with a list of argument values, e.g.

    The Math.max([value1[,value2, ...]]) function returns the largest of zero or more numbers.

    Math.max(10, 20); // 20
    Math.max(-10, -20); // -10
    Math.max(-10, 20); // 20
    

    The Math.max() method doesn't allow you to pass in an array. If you have a list of values of which you need to get the largest, you would normally call this function using Function.prototype.apply(), e.g.

    Math.max.apply(null, [10, 20]); // 20
    Math.max.apply(null, [-10, -20]); // -10
    Math.max.apply(null, [-10, 20]); // 20
    

    However, as of the ECMAScript 6 you can use the spread operator:

    The spread operator allows an expression to be expanded in places where multiple arguments (for function calls) or multiple elements (for array literals) are expected.

    Using the spread operator, the above can be rewritten as such:

    Math.max(...[10, 20]); // 20
    Math.max(...[-10, -20]); // -10
    Math.max(...[-10, 20]); // 20
    

    When calling a function using the variadic operator, you can even add additional values, e.g.

    Math.max(...[10, 20], 50); // 50
    Math.max(...[-10, -20], 50); // 50
    

    Bonus:

    Spread operator enables you to use the array literal syntax to create new arrays in situations where in ES5 you would need to fall back to imperative code, using a combination of push, splice, etc.

    let foo = ['b', 'c'];
    let bar = ['a', ...foo, 'd', 'e']; // ['a', 'b', 'c', 'd', 'e']
    
    0 讨论(0)
  • 2020-11-21 06:59
    var max_of_array = Math.max.apply(Math, array);
    

    For a full discussion see: http://aaroncrane.co.uk/2008/11/javascript_max_api/

    0 讨论(0)
  • 2020-11-21 07:00

    One more way to do it:

    var arrayMax = Function.prototype.apply.bind(Math.max, null);
    

    Usage:

    var max = arrayMax([2, 5, 1]);
    
    0 讨论(0)
  • 2020-11-21 07:00

    Using Math.max() or Math.min()

    Math.max(10, 20);   //  20
    Math.min(-10, -20); // -20
    

    The following function uses Function.prototype.apply() to find the maximum element in a numeric array. getMaxOfArray([1, 2, 3]) is equivalent to Math.max(1, 2, 3), but you can use getMaxOfArray() on programmatically constructed arrays of any size.

    function getMaxOfArray(numArray) {
      return Math.max.apply(null, numArray);
    }
    

    Or with the new spread operator, getting the maximum of an array becomes a lot easier.

    var arr = [1, 2, 3];
    var max = Math.max(...arr); // 3
    var min = Math.min(...arr); // 1
    
    0 讨论(0)
  • 2020-11-21 07:00

    For a concise, modern solution, one can perform a reduce operation over the array, keeping track of the current minimum and maximum values, so the array is only iterated over once (which is optimal). Destructuring assignment is used here for succinctness.

    let array = [100, 0, 50];
    let [min, max] = array.reduce(([prevMin,prevMax], curr)=>
       [Math.min(prevMin, curr), Math.max(prevMax, curr)], [Infinity, -Infinity]);
    console.log("Min:", min);
    console.log("Max:", max);

    To only find either the minimum or maximum, we can use perform a reduce operation in much the same way, but we only need to keep track of the previous optimal value. This method is better than using apply as it will not cause errors when the array is too large for the stack.

    const arr = [-1, 9, 3, -6, 35];
    
    //Only find minimum
    const min = arr.reduce((a,b)=>Math.min(a,b), Infinity);
    console.log("Min:", min);//-6
    
    //Only find maximum
    const max = arr.reduce((a,b)=>Math.max(a,b), -Infinity);
    console.log("Max:", max);//35

    0 讨论(0)
  • 2020-11-21 07:02

    I had the same problem, I needed to obtain the minimum and maximum values of an array and, to my surprise, there were no built-in functions for arrays. After reading a lot, I decided to test the "top 3" solutions myself:

    1. discrete solution: a FOR loop to check every element of the array against the current max and/or min value;
    2. APPLY solution: sending the array to the Math.max and/or Math.min internal functions using apply(null,array);
    3. REDUCE solution: recursing a check against every element of the array using reduce(function).

    The test code was this:

    function GetMaxDISCRETE(A)
    {   var MaxX=A[0];
    
        for (var X=0;X<A.length;X++)
            if (MaxX<A[X])
                MaxX=A[X];
    
        return MaxX;
    }
    
    function GetMaxAPPLY(A)
    {   return Math.max.apply(null,A);
    }
    
    function GetMaxREDUCE(A)
    {   return A.reduce(function(p,c)
        {   return p>c?p:c;
        });
    }
    

    The array A was filled with 100,000 random integer numbers, each function was executed 10,000 times on Mozilla Firefox 28.0 on an intel Pentium 4 2.99GHz desktop with Windows Vista. The times are in seconds, retrieved by performance.now() function. The results were these, with 3 fractional digits and standard deviation:

    1. Discrete solution: mean=0.161s, sd=0.078
    2. APPLY solution: mean=3.571s, sd=0.487
    3. REDUCE solution: mean=0.350s, sd=0.044

    The REDUCE solution was 117% slower than the discrete solution. The APPLY solution was the worse, 2,118% slower than the discrete solution. Besides, as Peter observed, it doesn't work for large arrays (about more than 1,000,000 elements).

    Also, to complete the tests, I tested this extended discrete code:

    var MaxX=A[0],MinX=A[0];
    
    for (var X=0;X<A.length;X++)
    {   if (MaxX<A[X])
            MaxX=A[X];
        if (MinX>A[X])
            MinX=A[X];
    }
    

    The timing: mean=0.218s, sd=0.094

    So, it is 35% slower than the simple discrete solution, but it retrieves both the maximum and the minimum values at once (any other solution would take at least twice that to retrieve them). Once the OP needed both values, the discrete solution would be the best choice (even as two separate functions, one for calculating maximum and another for calculating minimum, they would outperform the second best, the REDUCE solution).

    0 讨论(0)
提交回复
热议问题