Grouping NSArray of NSDictionary based on a key in NSDictionay

坚强是说给别人听的谎言 提交于 2019-11-29 10:39:51

It's a little hard to tell if what you want is three different arrays where each one only contains entries with a specific Name value (as your first paragraph suggests) or if you want a single array where the entries are sorted by Name (as your second paragraph suggests). Regardless,

To sort orig by the value of the Name field:

NSArray *sortedByName = [orig sortedArrayUsingDescriptors:@[[NSSortDescriptor sortDescriptorWithKey:@"Name" ascending:YES]]];

To get a new array by selecting only entries with a specific value for Name:

NSArray *t1Only = [orig filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"Name = %@", @"T1"]];

If the desired output is an array of arrays, you can get there by building a dictionary keyed by the name attribute in the orig dictionaries:

- (NSArray *)collateByName:(NSArray *)original {

    NSMutableDictionary *collate  = [NSMutableDictionary dictionary];
    for (NSDictionary *d in original) {
        NSString *newKey = d[@"Name"];
        NSMutableArray *newValue = collate[newKey];
        if (!newValue) {
            newValue = [NSMutableArray array];
            collate[newKey] = newValue;
        }
        [newValue addObject:d];
    }
    return [collate allValues];
}

It's a little verbose, but clear, I think. If you want to decide the attribute to distinguish with programmatically, pass in another param called attribute and replace the literal @"Name" with it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!