2
votes

Using ActionScript 3, suppose I have an array of numbers, lets say: 1, 2, 3, 4, 5. Is there a way to easily search this array and return the index corresponding to an element that is >= 2.5 (which would be, 3, in this case), for example? I'm implementing this with a while and for loop, and seems pretty wordy. Thought there might be a method for this already, but haven't stumbled upon it in:

http://help.adobe.com/en_US/FlashPlatform/reference/actionscript/3/Array.html#every()

Otherwise, what would be a simple way to achieve it?

In case it helps, I'll use this to implement a straight-forward linear interpolation math routine, assuming one doesn't already exist I'm not aware of.

2

2 Answers

3
votes

I'm not aware of any firstIndexOf in ActionScript.

You could add it to an ArrayUtil class:

Given the array:

var array:Array = [ 1, 2, 3, 4, 5 ];

Pass it to the ArrayUtil function:

public static function firstIndexOf(array:Array, value:Number):int
{
    for(var i:uint = 0; i < array.length; i++)
    {
        if(array[i] >= value)
            return i;
    }

    // if not found, return -1
    return -1;
}
0
votes
var t:Array = [4,9,1,2,3,5,6];

function something(base:Number, array:Array):int
{
    var t:Array = array.slice();
    var h:Number = int.MAX_VALUE;
    var i:int = -1;

    while(t.length > 0)
    {
        var l:Number = t.pop();

        if(l >= base)
        {
            if(h > l)
            {
                h = l;
                i = t.length;
            }
        }
    }

    return i;
}

trace(something(2, t)); // at index [3]