views:

248

answers:

2

Possible duplicate: comparing-two-arrays

I have two NSArray and I'd like to create a new Array with objects from the second array but not included in the first array.

Example:

NSMutableArray *firstArray = [NSMutableArray arrayWithObjects:@"Bill", @"Ben", @"Chris", @"Melissa", nil];
NSMutableArray *secondArray = [NSMutableArray arrayWithObjects:@"Bill", @"Paul", nil];

The resulting array should be: 

[@"Paul", nil];

I solved this problem with a double loop comparing objects into the inner one.

Is there a better solutions ?

+2  A: 

If duplicate items are not significant in the arrays, you can use the minusSet: operation of NSMutableSet:

NSMutableArray *firstArray = [NSMutableArray arrayWithObjects:@"Bill", @"Ben", @"Chris", @"Melissa", nil];
NSMutableArray *secondArray = [NSMutableArray arrayWithObjects:@"Bill", @"Paul" nil];

NSSet *firstSet = [NSSet setWithArray:firstArray];
NSMutableSet *secondSet = [NSMutableSet setWithCapacity:[secondArray count]];
[secondSet addObjectsFromArray:secondArray];

NSSet *result = [secondSet minusSet:firstSet];
teabot
+3  A: 
[secondArray removeObjectsInArray:firstArray];

This idea was taken from another answer.

Jean Regisser
That's a nice answer - better than my solution. And good job in locating the duplicate!
teabot