Created
July 20, 2018 03:50
-
-
Save dhl613/2885e4049e14b02837027dca5be46c9c to your computer and use it in GitHub Desktop.
iOS 数组归类分组 数组以年分组
This file contains hidden or 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
/// 待分组数据 以年为单位分组 | |
NSMutableArray *data = [NSMutableArray array]; | |
for (int i = 2018; i > 2010; i--) { | |
NSString *typeValue = [NSString stringWithFormat:@"%d年",i]; | |
for (int j = 1; j < 5; j++) { | |
NSString *other = [NSString stringWithFormat:@"月份: %d月",j+(arc4random() % 5)]; | |
[data addObject:@{@"year":typeValue,@"month":other}]; | |
} | |
} | |
[data addObject:@{@"year":@"2019年",@"month":@"月份 1月"}]; | |
NSArray *array = [data copy]; | |
/// year属性数组 | |
NSArray *tmpArr = [array valueForKeyPath:@"year"]; | |
/// 有序set year去重 | |
NSOrderedSet *set = [[NSOrderedSet alloc] initWithArray:tmpArr]; | |
NSArray *sectionArr = [set array]; | |
/// 分组 结果数组 | |
NSMutableArray *groupArr = [NSMutableArray array]; | |
/// 遍历去重后的year数组 | |
[sectionArr enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) { | |
/// 以year过滤原数组 | |
NSPredicate *pre = [NSPredicate predicateWithFormat:@"year == %@",obj]; | |
NSArray *indexArr = [array filteredArrayUsingPredicate:pre]; | |
[groupArr addObject:indexArr]; | |
}]; | |
NSLog(@"分组后: %@",groupArr); | |
NSLog(@"分组前: %@",array); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment