Remove duplicates from array comparing the properties of its objects

前端 未结 6 1312
隐瞒了意图╮
隐瞒了意图╮ 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:03

    NSMutableArray *leftObjects = [duplicateArray mutableCopy];
    NSMutableArray *nonDuplicates = [NSMutableArray new];
    while (leftObjects.count > 0)
    {
        YourClass *object = [leftObjects objectAtIndex:0];
    
        // find all objects matching your comaprison equality definition for YourClass
        NSArray *matches = [leftObjects filteredArrayUsingPredicate:
                            [NSPredicate predicateWithBlock:^BOOL(YourClass *evaluatedObject, NSDictionary *bindings)
                             {
                                 return (evaluatedObject.name == object.name);
                             }] ];
        [leftObjects removeObjectsInArray:matches];
    
        // add first object (arbitrary, may decide which duplicate to pick)
        [nonDuplicates addObject:matches.firstObject];
    }
    

提交回复
热议问题