3

At first sight it's very simple, but I'm having some problems to do this without using a lot of nested loops.

Example:

var father:Array = new Array(0,1,2,3,4,5);
var son:Array = new Array(3,4,5);

father.contains(son) // returns true or 4(the starting index if the contained array)

2 Answers 2

5

ActionScript 3 actually supports some slightly crazy stuff, due to the fact that, in the early days, Adobe/Macromedia were trying to make it compliant with Ecmascript.

So... you can do this:

var a1:Array = [1,2,3,4,5,6,7,8,9];
var a2:Array = [3,4,5];

// borrow String's indexOf function, and it magically works on Arrays
// but rename it because Array already has a different indexOf function
a1.indexOf2 = String.prototype.indexOf;

trace(a1.indexOf2(a2) > -1); // true

But you need to be a little bit careful because it will convert all the elements to Strings for the equality test. For primitives, it mostly won't matter but it will break badly with objects as they'll all be converted to "[object Object]" or to whatever their toString() returns.

Also, if you wanted to use the actual index for anything, rather than just checking it's not -1, you have to divide by two, as the number is double what you'd expect. I don't exactly know why this is :)

If you need something more general and reliable, you'd be better off writing a function to do an explicit search. This is a quick example, which I just wrote so could easily be bug-ridden:

    public function find(haystack:Array, needle:Array):int 
    {
        var index:int = -1;
        while(index <= haystack.length - needle.length)
        {
            index++;
            index = haystack.indexOf(needle[0], index);
            for( var i:int = 1; i<needle.length; i++)
            {
                if(haystack[index+i] != needle[i])
                {
                    continue;
                }
            }
            if( i == needle.length)
            {
                return index;
            }
        }
        return -1;
    }
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks, worked just like I needed! Just for curiosity, how do you discovered that?
I have been using Flash since before it had Actionscript at all, so I've seen the language grow from nothing and all the little warts along the way :)
0

Try this for simplicity:

// Determines if an array contains en element (similar to the PHP function with the same name)
public function in_array(needle:*, haystack:Array):Boolean 
{
    for each (var element:* in haystack)
    {
        if (element == needle) {return true;}
    }
    return false;
}

Comments

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.