How to check array value not exist in another arra

2019-07-30 01:30发布

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.

3条回答
贪生不怕死
2楼-- · 2019-07-30 02:29

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!

查看更多
冷血范
3楼-- · 2019-07-30 02:32

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];
查看更多
Luminary・发光体
4楼-- · 2019-07-30 02:33
NSMutableSet *set = [NSMutableSet setWithArray:arrOne];
[set intersectSet:[NSSet setWithAray:arrTwo];
return [set allObjects];
查看更多
登录 后发表回答