Find the min/max element of an Array in JavaScript

前端 未结 30 2062
無奈伤痛
無奈伤痛 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 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;Xc?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;XA[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).

提交回复
热议问题