Sunday, January 23, 2011

Get highest and lowest number values from an Array using AS3

Today we'll learn how to get the highest and lowest numeric value from an array.

Say, you have an array of numbers with over 100 elements and you need to find the highest and lowest values. How do you do that?

Way 1:

You can do that by using these two simple functions:

function maxVal(givenArray):Number
{
var max = givenArray[0];
for (var ma:int = 0; ma<givenArray.length; ma++)
{
if (givenArray[ma] > max)
{
max = givenArray[ma];
}
}
return max;
}

function minVal(givenArray):Number
{
var min = givenArray[0];
for (var mi:int = 0; mi<givenArray.length; mi++)
{
if (givenArray[mi] < min)
{
min = givenArray[mi];
}
}
return min;
}


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.

Way 2:

function maxVal(givenArray):Number
{
return Math.max.apply(this, givenArray);
}

function minVal(givenArray):Number
{
return Math.min.apply(this, givenArray);
}

We use the built-in Math.max function and feed it the givenArray.

Example of using the functions:

var numbersArray:Array = [5, 21, 876, 5465, 234, 1, 0.1, 354, 3476];

trace(maxVal(numbersArray), minVal(numbersArray));

Output: 5465 and 0.1.

Thanks for reading!

1 comment:

Anonymous said...

Awesome, Thank you!!

Post a Comment