在APP开发中经常碰到这种情况,后台给的数据需要我们按照某种条件分组。比如我的项目中:需要把数组中的数据按照时间分类分组,同一天的数据放在一起比如8-20号的数据分一组,8-21号的数据分一组。代码如下:
其中_dataArray为需要分类的数组,_titleArray为分好组的数组。
//首先把原数组中数据的日期取出来放入timeArr
NSMutableArray *timeArr=[NSMutableArray array];
[_dataArray enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
NSDictionary *currentDict=obj;
NSString *time1=[currentDict objectForKey:@"birthTime"];
NSString *month1=[[[[time1 componentsSeparatedByString:@" "] firstObject] componentsSeparatedByString:@"-"] objectAtIndex:1];
NSString *day1=[[[[time1 componentsSeparatedByString:@" "] firstObject] componentsSeparatedByString:@"-"] objectAtIndex:2];
NSString *currentStr1=[month1 stringByAppendingString:day1];
[timeArr addObject:currentStr1];
}];
//使用asset把timeArr的日期去重
NSSet *set = [NSSet setWithArray:timeArr];
NSArray *userArray = [set allObjects];
NSSortDescriptor *sd1 = [NSSortDescriptor sortDescriptorWithKey:nil ascending:NO];//yes升序排列,no,降序排列
//按日期降序排列的日期数组
NSArray *myary = [userArray sortedArrayUsingDescriptors:[NSArray arrayWithObjects:sd1, nil]];
//此时得到的myary就是按照时间降序排列拍好的数组
_titleArray=[NSMutableArray array];
//遍历myary把_titleArray按照myary里的时间分成几个组每个组都是空的数组
[myary enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSMutableArray *arr=[NSMutableArray array];
[_titleArray addObject:arr];
}];
//遍历_dataArray取其中每个数据的日期看看与myary里的那个日期匹配就把这个数据装到_titleArray 对应的组中
[_dataArray enumerateObjectsUsingBlock:^(id _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
NSDictionary *currentDict=obj;
NSString *time1=[currentDict objectForKey:@"birthTime"];
NSString *month1=[[[[time1 componentsSeparatedByString:@" "] firstObject] componentsSeparatedByString:@"-"] objectAtIndex:1];
NSString *day1=[[[[time1 componentsSeparatedByString:@" "] firstObject] componentsSeparatedByString:@"-"] objectAtIndex:2];
NSString *currentStr1=[month1 stringByAppendingString:day1];
for (NSString *str in myary)
{
if([str isEqualToString:currentStr1])
{
NSMutableArray *arr=[_titleArray objectAtIndex:[myary indexOfObject:str]];
[arr addObject:currentDict];
}
}
}];