Banzboy
Banzboy

Reputation: 113

How to check if values in array A is in array B?

I ran into a bit of pickle lately, I'm trying to compare these two arrays.

Array1 = ["Red","Green","Blue","Yellow","Black"];

Array2 = ["Green","Violet","Black","White"];

I want to know if all the values in Array2 are not in Array 1. So what I came up with was this:

for(var i:int=0;i<Array2.length;i++)
{
    if(Array1.indexOf(Array2[i]) == -1)
    {
        trace("No String found!")
    }
} 

Right now it gives me a trace every time it can't find a value. The issue I have is that I want it to perform the trace only if all the values in the Array2 are not in Array1.

Does any body have an idea?

Upvotes: 0

Views: 153

Answers (2)

Daniel
Daniel

Reputation: 35684

I want to know if all the values in Array2 are not in Array 1

do you mean all or any? for all you could use (read: complicate by) this casalib arrayUtil class: http://as3.casalib.org/docs/org_casalib_util_ArrayUtil.html#containsAll

This function compares if ALL values are present, there are other functions there too that might be of help.

Upvotes: 0

aust
aust

Reputation: 914

The best method is to search until a value is found, then exit the loop. If a value isn't found, it will naturally exit and the flag will remain false. You then check to see if the flag is true/false and perform your actions accordingly.

Try this:

var found:Boolean = false;
for(var i:int = 0; i < Array2.length && !found; i++)
{
    found = Array1.indexOf(Array2[i]) == -1;
}

if (!found)
{
    trace("No String found!");
}

Upvotes: 2

Related Questions