1

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.

2
  • 1
    Where is the problem? Can't you just loop through ArrTwo and then check if every element is in ArrOne and if not just delete it?
    – SIGKILL
    Commented Mar 8, 2013 at 2:50
  • Try this solution. This works for me. :) Commented Dec 6, 2015 at 19:58

3 Answers 3

4
NSMutableSet *set = [NSMutableSet setWithArray:arrOne];
[set intersectSet:[NSSet setWithAray:arrTwo];
return [set allObjects];
4
  • +1, but you didnt completely answer the question. You need to add [ArrTwo removeObjectsInArray:[set allObjects]]; as well.
    – iDev
    Commented Mar 8, 2013 at 3:07
  • This will only return intersect value. How can I know which one I should delete.
    – bobShawal
    Commented Mar 8, 2013 at 3:42
  • 1
    @bobShawal, You can use [ArrTwo removeObjectsInArray:[set allObjects]]; after the above code instead of replace. Or else check the answer which will also work for you.
    – iDev
    Commented Mar 8, 2013 at 4:09
  • The answer is correct. If he removes the values in the set from arrTwo he gets the an array containing the values that ARE NOT in arrOne. But that's not what the user asked. Commented Mar 12, 2014 at 9:38
3

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];
1

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!

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.