3

Let's say I have two arrays:

NSArray * first = @[@"One", @"Two", @"Three"," @Four"];
NSArray * second = @[@"Four", @"Five", @"Six", @"One"];

I want to put the objects that are in both into another array:

NSArray * both = @[@"Four", @"One"]; 

Is there a more elegant way than going through each item of the first one and checking if its contained in the second?

jscs
  • 63,694
  • 13
  • 151
  • 195
DanielR
  • 701
  • 2
  • 12
  • 24

3 Answers3

9

You basically need to find the intersection of the arrays so you need to use set here:

NSMutableSet *intersection = [NSMutableSet setWithArray:firstArray];
[intersection intersectSet:[NSSet setWithArray:secondArray]];

NSArray *resultArray = [intersection allObjects];
Saurabh Passolia
  • 8,099
  • 1
  • 26
  • 41
1

Create 2 instances of NSMutableSet from your 2 arrays. Then do:

NSArray *result = [[set1 intersectSet:set2] allObjects];
Wain
  • 118,658
  • 15
  • 128
  • 151
1

Sure. Just use the right tool for the right task. Alias, use sets for set operations.

NSSet *first = [NSSet setWithArray:array1];
NSMutableSet *second = [NSMutableSet setWithArray:array2];
[second intersectSet:first];
NSArray *commonObjects = [second allObjects];