iosobjective-cnsmutablearraynsorderedset

Best way to remove duplicate objects from multi dimension MutableArray objective-C


I'm looking for the best solution to remove duplicate objects from multi dimension array in objective-C (Swift is also fine) from some array like this:

muliDemensionArray = @[
                                 @[@"1", @"2", @"3", @"4", @"4",],
                                 @[@"11", @"13", @"24", @"14",],
                                 @[@"1", @"3", @"24", @"21",],
                                 ];

Do we have any algorithm or solution from NSOrderedSet/NSMutableArray support us to do this without loop/ reduce loop as much as possible?

This is expected result to remove all duplicates across all arrays:

mutilDemensionArray = @[
                                 @[@"1", @"2", @"3", @"4",],
                                 @[@"11", @"13", @"24", @"14",],
                                 @[@"21",],
                                 ];

Solution

  • You can use the property of NSSets that they will only store a single instance of a given value.

    Something like:

    -(NSArray *)removeDuplicatesFromArray:(NSArray *)array {
    
        NSMutableArray *returnArray=[NSMutableArray new];
        NSMutableSet *cumulativeSet=[NSMutableSet new];
    
        for (NSArray *innerArray in array) { 
            NSMutableSet *innerSet = [NSMutableSet setWithArray:innerArray];
            [innerSet minusSet:cumulativeSet];
            [cumulativeSet unionSet:innerSet];
    
            [returnArray addObject:[innerSet allObjects]];
        }
    
        return [returnArray copy];
     }