Search code examples
iosobjective-cnsmutablearraynsarrayduplicates

Remove duplicate values from NSArray while appending


I have 2 arrays, one of which is NSMutableArray (say mutArrayA) and other is NSArray(arrayB). I am appending arrayB to mutArrayA and at the same time I want to remove duplicates if any i.e. I don't want any duplicates in mutArrayA.

One way I know to do this is iterating over each object in the arrayB and checking its index using indexOfObject which if found in mutArrayA, then don't append that object to mutArrayA else append it. However I was trying to look for some quicker way to do this and I came across the following solution on this site which goes as below:

[mutArrayA setArray:[[NSSet setWithArray:arrayB] allObjects]];

When I execute this, my mutArrayA gets replaced with objects in arrayB because of setArray. Is there a quicker way using which I can append the array without getting the duplicates.


Solution

  • [mutArrayA addObjectsFromArray:[[NSSet setWithArray:arrayB] allObjects]];
    [mutArrayA setArray:[[NSSet setWithArray:mutArrayA] allObjects]];
    

    So initially you remove duplicates from arrayB, append it, and then apply the same principle to remove duplicates from mutArrayA if there are any after appending

    UPDATE

    You need to override isEqual: method for your class. I'll give you an example by assuming your objects contain NSString objects.

    - (BOOL)isEqual:(MyClass *)object
    {
      return [self.key isEqualToString:object.key] && [self.value isEqualToString:object.value];
    }
    

    You need also to override hash method like this:

    - (NSUInteger)hash {
    return [self.key hash] ^ [self.value hash];
    }
    

    The problem is NSSet doesn't remove duplicates cause it thinks they're are not duplicates so by overriding this method you give it a clue of how to compare your objects for equality