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




ActionScript 3. 0 Cookbook
ActionScript 3.0 Cookbook: Solutions for Flash Platform and Flex Application Developers
ISBN: 0596526954
EAN: 2147483647
Year: 2007
Pages: 351

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net