views:

310

answers:

2

I have two NSArrays, what I'm looking to do is to compare two arrays which contain strings, find the similarities and create the first array again but so they have no similarities.

Just for an example something like.

Two Arrays:

NSArray *arrayOne = [NSArray arrayWithObjects:@"TD1", @"TD2", @"TD3", nil];
NSArray *arrayTwo = [NSArray arrayWithObjects:@"Blah", @"String", @"TD2", nil];

Outcome:

NSArray *arrayOne = [NSArray arrayWithObjects:@"TD1", @"TD2", @"TD3", nil];

NSArray *arrayOneCopy = [NSArray arrayWithObjects:@"TD1", @"TD3", nil];
NSArray *arrayTwo = [NSArray arrayWithObjects:@"Blah", @"String", @"TD2", nil];
+9  A: 
NSMutableArray *arrayOneCopy = [NSMutableArray arrayWithArray:arrayOne];
[arrayOneCopy removeObjectsInArray:arrayTwo];
newacct
Thanks Very Much!
Joshua
+8  A: 

Use NSSet.

NSSet *setOne = [NSMutableSet setWithArray: arrayOne];
NSSet *setTwo = [NSSet setWithArray: arrayTwo];

[setOne minusSet: setTwo];

NSArray *arrayOneResult = [setOne allObjects];

Or use NSArray as the other person answered -- that works, too.

Which one works depends entirely on your data set size. For small sets of data, the array solution works fine. For larger sets, NSSet will be much more efficient in that membership tests are a hash check and not a linear search.

Measure and use the one that works best.

bbum
If the order of the items in the array is important, then I guess one would have to use the other solution with NSArray, right?
Thomas Müller
Good answer, but like you said, I am only using small sets of data so I am going to use the other solution. Thanks Anyway!
Joshua
Yup-- for small data sets, "newacct"'s answer is the way to go.
bbum