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",],
];
You can use the property of NSSet
s that they will only store a single instance of a given value.
First convert each sub-array into a set, that will remove duplicates that are in that array.
Then, subtract the set of items that have already been seen.
Convert the result back to an array and add it to your output array.
Finally, add the items in that sub-array to the set of items that have already been seen.
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];
}