Last active
December 9, 2015 21:44
-
-
Save HenningBrandt/22444daf1b91f99139af to your computer and use it in GitHub Desktop.
Neat snippet to group objects in an NSArray based on equal values under a given keypath.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@implementation NSArray (GroupBy) | |
- (NSArray *)groupByKeyPath:(NSString *)keyPath { | |
NSArray *distinctValues = [self valueForKeyPath:[@"@distinctUnionOfObjects." stringByAppendingString:keyPath]]; | |
NSMutableArray *result = [NSMutableArray arrayWithCapacity:[distinctValues count]]; | |
for (id groupValue in distinctValues) { | |
NSString *predicateFormat = [NSString stringWithFormat:@"(%@ == %%@)", keyPath]; | |
NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateFormat, groupValue]; | |
NSArray *group = [self filteredArrayUsingPredicate:predicate]; | |
[result addObject:group]; | |
} | |
return result; | |
} | |
@end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment