How to check array value not exist in another arra

2019-07-30 01:58发布

问题:

I have two different NSMutabelArray ArrOne and ArrTwo. Letsay ArrOne = A, B, C and D ArrTwo = C, D, X and Y. So i need to check if the value of ArrTwo is same as ArrOne and remove item from ArrTwo if it is not same as in ArrOne. In this case, i have to remove X and Y from ArrTwo. Please give me an idea.

回答1:

NSMutableSet *set = [NSMutableSet setWithArray:arrOne];
[set intersectSet:[NSSet setWithAray:arrTwo];
return [set allObjects];


回答2:

You can do it with indexesOfObjectsPassingTest, like this:

    NSMutableArray *a = [@[@"A",@"B",@"C",@"D"] mutableCopy];
    NSMutableArray *b = [@[@"C",@"D",@"X",@"Y"] mutableCopy];

    NSIndexSet *indxs = [b indexesOfObjectsPassingTest:^BOOL(NSString *obj, NSUInteger idx, BOOL *stop) {
        return ![a containsObject:obj];
    }];

    [b removeObjectsAtIndexes:indxs];


回答3:

I found a solution and it works

for (int i=0; i< arrTwo.count; i++)
{ 
    if(![arrOne containsObject:[arrTwo objectAtIndex:i]])
    {
         //do action
         NSLog(@"do delete %@",[arrTwo objectAtIndex:i]);
     }
}

Thanks!