2

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 Answers 2

3

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;
}
Sign up to request clarification or add additional context in comments.

4 Comments

Oops - I forgot to add a -1 return in case no value was greater in the set. Maybe this should be named differently as well - firstIndexGreaterThan(...)
For completeness, I think the for loop assignment should extend to (array.length-1) since indexing begins at 0.
i < array.length will stop at array.length - 1.
Oops, my mistake (I always use <= in my expressions!).
0
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]

2 Comments

Thanks Marty, I hadn't thought of using pop like this.
Unless your arrays are ridiculously massive and/or this is being run very frequently, I don't think you will run into any troubles.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.