0

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];
        }
    }
Win Coder
  • 6,628
  • 11
  • 54
  • 81
  • Which of these arrays are the 2 arrays you'd like to combine and which array are you putting the result into? – Lyndsey Scott Dec 01 '14 at 12:59
  • Basically you should just ignore this code as it was a work in progress i was just looking for an algorithm according to the situation – Win Coder Dec 01 '14 at 13:05
  • 1
    How would you decide which of the duplicates to remove if everything but those 2 field is different? – Lyndsey Scott Dec 01 '14 at 13:26

2 Answers2

0

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;
}
user1502383
  • 323
  • 1
  • 5
0

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];
   }
}
Mateusz
  • 1,222
  • 11
  • 22