Remove duplicates from array comparing the properties of its objects

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

    You can create an NSMutableSet of dates, iterate your event list, and add only events the date for which you have not encountered before.

    NSMutableSet *seenDates = [NSMutableSet set];
    NSPredicate *dupDatesPred = [NSPredicate predicateWithBlock: ^BOOL(id obj, NSDictionary *bind) {
        Event *e = (Event*)obj;
        BOOL seen = [seenDates containsObject:e.date];
        if (!seen) {
            [seenDates addObject:e.date];
        }
        return !seen;
    }];
    NSArray *events = ... // This is your array which needs to be filtered
    NSArray *filtered = [events filteredArrayUsingPredicate:dupDatesPred];
    

提交回复
热议问题