iosobjective-cnsmutablearraynsarraynsmutableset

Removing Duplicate Custom Objects from two arrays and combining them


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];
        }
    }

Solution

  • 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];
       }
    }