2

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

Hi - I'm trying to use flash's Math.max() functionality to find the highest of a set of numbers. Normally, these are input via a comma delimited string of numbers, but I need to have it loop through a series of numbers in an array. What is the proper syntax for this? I tried:

var maxMemberWidth = int(Math.max(
    for (var k=0;k<memberClips.length;k++){
        memberClips[i].memeberWidth;
    }
));

but that's obviously not right. I have a feeling the answer involves running some sort of separate function and returning the values to this function, but I haven't quite gotten the syntax right yet.

Community
  • 1
  • 1
mheavers
  • 29,530
  • 58
  • 194
  • 315

3 Answers3

1

You can try this instead:

var max_number:Number = memberClips[0];

for( var i:int = 1; i < memberClips.length; i++ )
{
    max_number = Math.max( max_number, memberClips[i] );
}

What this does is initializes the maximum number to the first element of your array and then loops through all the elements in your array until it reaches the end of the array. You'll then have the maximum number you're seeking. The index variable i is initialized to 1 because you don't need to compare the first element against itself. You should take note that this code also assumes that you have at least one element in your array.

  • Thanks - I actually just found a pretty good method here: http://stackoverflow.com/questions/424800/what-is-the-best-way-to-get-the-minimum-or-maximum-value-from-an-array-of-numbers – mheavers May 05 '11 at 19:21
1

Your aproach is not ALL wrong, you can do this:

// note the apply in the next line!
var maxMemberWidth:int = int(Math.max.apply(null, AllMembersWidth()));

...

private function AllMembersWidth():Array
{
    var widths:Array = [];
    for (var k:int = 0; k < memberClips.length; k++)
        widths[k] = memberClips[k].memeberWidth;
    return widths;
}

This works even when you have an empty array (it returns -Infinity)

Lucas Gabriel Sánchez
  • 40,116
  • 20
  • 56
  • 83
1

More condensed version, not as sexy looking as it would be on ruby but it works.

var widths:Array = clips.map( function(o:*, i:int, a:Array):* { return o.width; } );

var max:Number = Math.max.apply(null, widths);
var min:Number = Math.min.apply(null, widths);
Casper Beyer
  • 2,203
  • 2
  • 22
  • 35