Last Updated: February 25, 2016
· _jeffreyjackson

Merging 2 NSArrays & Duplicates

You have two NSArrays and you want to merge them into 1 Array.

Easy. You need to know about NSSet and maybe a little 'Set Theory'.

NSMutableSet *mergedSet = [NSMutableSet setWithArray:arrayFirst];
[mergedSet unionSet:[NSSet setWithArray:arraySecond]];

In Set Theory, a union will automatically remove your duplicates. In the case you only wanted to know about duplicates, then take a look at intersectSet:

Take your new set one step further by sorting them alphabetically with a block:

arraySorted = [[mergedSet allObjects] sortedArrayUsingComparator:^NSComparisonResult(id a, id b) {
            NSString *first = [a objectForKey:@"identifier"];
            NSString *second = [b objectForKey:@"identifier"];
            return [first compare:second];