Remove duplicates from array comparing the properties of its objects

前端 未结 6 1289
隐瞒了意图╮
隐瞒了意图╮ 2021-02-04 03:50

Suppose I have a class Event, and it has 2 properties: action (NSString) and date (NSDate).

And suppose I have an array of Event objects. The problem is that \"date\" pr

6条回答
  •  野性不改
    2021-02-04 04:17

    I think the most effective way is to use NSDictionary to store the object as value and the property value as key, and before adding any object to the dictionary you check if it exist or not which is O(1) operation, i.e. the whole process will take O(n)

    Here is the code

    - (NSArray *)removeDuplicatesFromArray:(NSArray *)array onProperty:(NSString *)propertyName {
        NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
    
        for (int i=0; i

    you can use it as the following

    self.arrayWithObjects = [self removeDuplicatesFromArray:self.arrayWithObjects onProperty:@"when"]; 
    

提交回复
热议问题