You can use NSSet as a filter (think of Venn diagrams in the head):
NSArray *array1 = @[@1,@2,@3,@4,@2,@3]; NSArray *array2 = @[@3,@4,@5,@6,@4,@6]; NSSet *set1 = [NSSet setWithArray:array1]; // [1,2,3,4] NSSet *set2 = [NSSet setWithArray:array2]; // [3,4,5,6]
METHOD 1 (my favorite):
NSMutableSet *mSet1 = [set1 mutableCopy]; NSMutableSet *mSet2 = [set2 mutableCopy]; [mSet1 minusSet:set2];
METHOD 2 (more explicit test, no need for Venn diagrams):
NSSet *setOfObjsUniqueTo1 = [set1 objectsPassingTest:^BOOL(id _Nonnull obj, BOOL * _Nonnull stop) { return ![set2 containsObject:obj]; }];
METHOD 3 (
NSSet
not worth it, but I would not put this code opposite the Queen of England at an official dinner - this is inelegant):
NSMutableArray *mArray1 = [NSMutableArray new]; NSMutableArray *mArray2 = [NSMutableArray new]; NSIndexSet *uniqueIndexes1 = [array1 indexesOfObjectsPassingTest:^BOOL(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { return ![array2 containsObject:obj]; }]; // [0,1,4] (b/c @1 and @2 are unique to array1) [uniqueIndexes1 enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) { [mArray1 addObject:array1[idx]]; }]; // @[@1,@2,@2] NSIndexSet *uniqueIndexes2 = [array2 indexesOfObjectsPassingTest:^BOOL(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { return ![array1 containsObject:obj]; }]; // [2,3,5] (b/c @5 and @6 are unique to array2) [uniqueIndexes2 enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL * _Nonnull stop) { [mArray2 addObject:array2[idx]]; }]; // @[@5,@6,@6] NSArray *unionArray = [array1 arrayByAddingObjectsFromArray:array2]; // @[@1,@2,@2,@5,@6,@6] NSArray *yetAnotherArrayOfUniqueness = [[NSSet setWithArray:unionArray] allObjects]; // @[@1,@2,@5,@6]
Not a question of the questionnaire, but to remove an array with duplicates (i.e. where each element is unique), similar magic can be performed:
According to Apple Docs (highlighted by me):
+ setWithArray: Creates and returns a set containing a collection of uniqued objects contained in this array.
UPDATE: And look at a similar question here: Delete all duplicate rows in NSArray