在一个array中有一个model,类似这样:
[
model1.date = 2016.4.12 8:25
model2.date = 2016.4.12 9:20
model3.date = 2016.3.13 8:30
model4.date = 2016.3.11 8:15
model5.date = 2015.2.12 1:20
model6.date = 2015.2.12 2:25
]
现在需要做的是将日期是同一天的放入一个数组中,没有日期相同的也放入一个数组中,最终要得到的数组应该是这样的:
[
[model1,model2],
[model3],
[model4],
[model5,model6],
]
请问,应该如何做?
这是json?直接
var keymap={};
然后遍历这个list
判断keymap[item.date]是否为undefined
是则将它赋值为一个array
否就将item push进去
最后遍历一个keymap,将所有的value push进一个list
首先,题主你的model.date是NSString类型,还是NSDate?日期格式不是“yyyy.MM.dd HH.mm”?
先抛开这些问题,针对题主给出的数据格式,提供一种思路,假设model.date是NSString类型(若是NSDate类型,则转成NSString类型)。
1.遍历这个数组,首先将model.date去除首尾空格
str = [model.date stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
2.再从str截取头部到第一个空格间的子串,例如:"2016.4.12 8:25"截取"2016.4.12",然后通过比较str就知道要把对应model放在哪个array
NSRange range = [str rangeOfString:@" "];
NSString *subStr = [str substringToIndex:range.location];
写了个Demo验证下,以下附上代码
//原始数组
NSArray *array = @[[Model modeWithDate:@"2016.4.12 8:25"],
[Model modeWithDate:@"2016.4.12 9:20"],
[Model modeWithDate:@"2016.3.13 8:30"],
[Model modeWithDate:@"2016.3.11 8:15"],
[Model modeWithDate:@"2015.2.12 1:20"],
[Model modeWithDate:@"2015.2.12 2:25"]];
NSLog(@"array:%@",array);
NSMutableArray *dateArray = [NSMutableArray array];
for (Model *item in array) {
if (![item isKindOfClass:[Model class]]) {
return;
}
//去除首尾空格
NSString *dateStr = [item.date stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
//截取从头部到空格之间的字符串
NSRange range = [dateStr rangeOfString:@" "];
NSString *str = [dateStr substringToIndex:range.location];
BOOL isContain = NO;
for (NSMutableArray *arrayItem in dateArray) {
Model *firstModel = [arrayItem firstObject];
NSString *firstDateStr = [firstModel.date stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
NSRange spaceRange = [firstDateStr rangeOfString:@" "];
NSString *firstStr = [firstDateStr substringToIndex:spaceRange.location];
if ([firstStr isEqualToString:str]) {
isContain = YES;
[arrayItem addObject:item];
break;
}
}
if (!isContain) {
[dateArray addObject:[NSMutableArray arrayWithObject:item]];
}
}
NSLog(@"dateArray:%@",dateArray);
对应的控制台输出:
观察model的内存地址,验证是没问题的。
假如,model.date是NSDate类型,也可以将model.date转成"yyyy-MM-dd"的字符串,再去对比这串字符串也是可以的,希望我的回答对你有帮助。