What is the best way to get the minimum or maximum value from an Array of numbers?

后端 未结 18 1029
日久生厌
日久生厌 2020-11-27 03:00

Let\'s say I have an Array of numbers: [2,3,3,4,2,2,5,6,7,2]

What is the best way to find the minimum or maximum value in that Array?

Right now,

18条回答
  •  情歌与酒
    2020-11-27 03:58

    Shortest way :

    Math.min.apply(null,array); //this will return min value from array
    Math.max.apply(null,array); //this will return max value from array

    otherway of getting min & max value from array

     function maxVal(givenArray):Number
        {
        var max = givenArray[0];
        for (var ma:int = 0; ma max)
        {
        max = givenArray[ma];
        }
        }
        return max;
        }
    
        function minVal(givenArray):Number
        {
        var min = givenArray[0];
        for (var mi:int = 0; mi

    As you can see, the code in both of these functions is very similar. The function sets a variable - max (or min) and then runs through the array with a loop, checking each next element. If the next element is higher than the current, set it to max (or min). In the end, return the number.

提交回复
热议问题