## Question of the Week

 Finding Maximum/Minimum Value in an Array        by kirupa  |  1 July 2005I was a bit dismayed to find out that Flash had no simple built-in way of getting the maximum value from an array. You have Math.max(), but that function returns only the greater of two values. The Array.sort and Array.sortOn methods were too complicated for me to fiddle with, and when I thought I had them working, they didn't produce the right results. In this short tutorial, I will provide the code for finding the maximum and minimum values in an array. I will conclude with a brief explanation of the ideas behind why the code work with an explanation of the code itself. Code for Finding the Maximum Value in an Array: maxValue = function (array) { mxm = array[0]; for (i=0; imxm) { mxm = array[i]; } } return mxm; }; Code for Finding the Minimum Value in an Array: minValue = function (array) { mn = array[0]; for (i=0; imxm) { mxm = array[i]; } } I initiate a simple loop that counts from 0 until it reaches the end of our array. This is representative of me progressing through each value in our array until I reach the end. if (array[i]>mxm) { mxm = array[i]; } In these lines of code, I first check if the number in our array at position i is greater than our maximum value. If it is, I set our current value to be our new maximum. If our current value is not greater than our current maximum, I just don't do anything. return mxm; After all is said and done, and our value of i is less than the length of our array, I return the maximum value, mxm. In short, that is what our function, in the end outputs - just the maximum value as determined by all of our above work. For the minimum, the only difference is that array[i] > mxm is replaced with array[i] < mn, where mxm and mn are similar variables that store our temporary maximums and minimums. If you are interested in not only finding the maximum/minimum but also the position at which the maximum/minimum occurs, you may find the following article at Layer 51 useful: http://proto.layer51.com/d.aspx?f=254 Thanks to lostinbeta for providing me with the URL. Just a final word before we wrap up. If you have a question and/or want to be part of a friendly, collaborative community of over 220k other developers like yourself, post on the forums for a quick response!