Skip to content

Instantly share code, notes, and snippets.

@saiday
Created March 6, 2015 13:22
Show Gist options
  • Select an option

  • Save saiday/de8ed34e88f9e096441f to your computer and use it in GitHub Desktop.

Select an option

Save saiday/de8ed34e88f9e096441f to your computer and use it in GitHub Desktop.
NSArray group by
- (NSDictionary *)groupByKey:(NSString *)key
{
NSMutableDictionary *dictionary = [NSMutableDictionary dictionary];
for (id obj in self) {
id keyValue = [obj valueForKey:key];
if (keyValue) {
NSMutableArray *array = dictionary[keyValue];
if (!array) {
array = [NSMutableArray array];
dictionary[keyValue] = array;
}
[array addObject:obj];
}
}
return [dictionary copy];
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment