Grouping NSArray of NSDictionary based on a key in NSDictionay

前端 未结 2 1546
一向
一向 2020-12-18 02:17

I am trying to filter out a NSArray of NSDictionaries. With my below example, I want dict1, dict2 & dict4 grouped in one array, dict3 & dict5 grouped in second array

2条回答
  •  旧时难觅i
    2020-12-18 02:57

    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.

提交回复
热议问题