Removing Duplicate Custom Objects from two arrays and combining them

887 views Asked by At

First off i have searched a lot but all methods seems to be for primitives or for whole custom objects.

My situation is this. I have a type custom objects in two different arrays. However the fields of every single objects is quite different to another with the exception of only 2 fields.

What i want is combine both of these arrays and then remove duplicates with respect to only those two fields.How can i do that. My Code so far

NSMutableArray* testArray = [eventHandler returnAllEvents];
    NSMutableArray* combinedArray = [[NSMutableArray alloc]init];
    NSArray* finalArray = [[NSArray alloc]init];
    if (testArray.count==0) {
        for (int i = 0; i<facebookData.count; i++) {
            LSEvent* event = [facebookData objectAtIndex:i];
            [combinedArray addObject:event];
        }
        finalArray = [combinedArray arrayByAddingObjectsFromArray:calendarData];
    }
    NSMutableArray *uniqueArray = [NSMutableArray array];
    NSMutableSet *names = [NSMutableSet set];
    for (id obj in finalArray) {
        NSString *destinationName = [obj destinationname];
        if (![names containsObject:destinationName]) {
            [uniqueArray addObject:obj];
            [names addObject:destinationName];
        }
    }
2

There are 2 answers

0
Mateusz On BEST ANSWER

You can do sth like this

NSArray first = ...
NSMutableArray second = ... // this will be combine array

for (id someObj in first) {
   if ( [second filteredArrayUsingPredicate:[self predicateForObject:someObj ]].count == 0 ){
       [second addObject: someObj];
   }
}
0
user1502383 On

If you want to check that object exists in array using containsObject: you need to implement - (BOOL)isEqual:(id)other in your custom object.

- (BOOL)isEqual:(id)other {
    if (other == self) {
      return YES;
    }
    if (!other || ![other isKindOfClass:[self class]]) {
      return NO;
    }
    if (self.identifier == other.identifier) {
      return NO;
    }
    return YES;
}