Recipe 5.13.
Getting the Minimum or Maximum Element
Problem
You want to retrieve the minimum or maximum
element from an array of numbers.
Solution
Sort the array numerically, and then retrieve
the first or last element from the sorted array.
Discussion
You can quickly retrieve the minimum or maximum
value from an array by sorting it. The following example
illustrates how to do just that:
var scores:Array = [10, 4, 15, 8];
scores.sort(Array.NUMERIC);
trace("Minimum: " + scores[0]);
trace("Maximum: " + scores[scores.length - 1]);
Of course, if the existing order of the array is
important, you'll want to make a copy of the array before sorting
it. See Recipe
5.8.
You can optionally use the ArrayUtilities.min( ) and
ArrayUtilities.max( ) methods.
See Also
Recipe
5.8
|