对数组合并同类项

去除同类项
使用NSMutableSet集合特性,及NSPredicate谓词过滤器,实现去重,分类,比较方便,有用到的,可以参考。

- (id) deleteTheSameObject:(NSArray *)objectArr condition:(NSString *)condition {
    
    NSMutableSet *set = [NSMutableSet set];
    
    [objectArr enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
       //自定义模型,可以自己替换数据
        BLDownloadItemModel *item = obj;
        //利用set不重复的特性,得到有多少组,根据数组中的courseId字段
        [set addObject:item.courseId];
    }];
    
    NSArray *sortDesc = @[[[NSSortDescriptor alloc] initWithKey:@"self" ascending:YES]];
    
    NSArray *sortSetArray = [set sortedArrayUsingDescriptors:sortDesc];
    
    __block NSMutableArray *groupArr = [NSMutableArray array];
    
    [sortSetArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        
        NSPredicate *predicate;
        
        if ([condition isEqualToString:@"courseId"])
        {
            predicate = [NSPredicate predicateWithFormat:@"courseId = %@", obj];
        } else if ([condition isEqualToString:@"parentId"])
        {
            predicate = [NSPredicate predicateWithFormat:@"parentId = %@", obj];
        } else
        {
            predicate = [NSPredicate predicateWithFormat:@"id = %@", obj];
        }
        NSArray *tempArr = [NSArray arrayWithArray:[objectArr filteredArrayUsingPredicate:predicate]];
        
        [groupArr addObject:tempArr];
    }];
    
    
    return groupArr;
}

你可能感兴趣的:(对数组合并同类项)