在一个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],
]
请问,应该如何做?
阿神2017-04-17 17:55:02
Is this json? Directly
var keymap={};
Then traverse the list
Determine whether keymap[item.date] is undefined
If yes, assign it to an array
If not, push the item in
Finally traverse a keymap and add all values Push into a list
伊谢尔伦2017-04-17 17:55:02
First of all, is your model.date of type NSString or NSDate? Is the date format not "yyyy.MM.dd HH.mm"?
Put aside these questions first and provide a data format based on the data format given by the questioner. The idea is that model.date is of NSString type (if it is NSDate type, it is converted to NSString type).
1. Traverse this array, first remove the leading and trailing spaces from model.date
str = [model.date stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceCharacterSet]];
2. Then intercept the substring from the head to the first space from str, for example: "2016.4.12 8:25" intercepts "2016.4.12", and then by comparing str, you will know which array to put the corresponding model in
NSRange range = [str rangeOfString:@" "];
NSString *subStr = [str substringToIndex:range.location];
Write a Demo to verify, the code is attached below
//原始数组
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);
Corresponding console output:
Observe the memory address of the model and verify that there is no problem.
If model.date is of NSDate type, you can also convert model.date into a string of "yyyy-MM-dd", and then compare this string. I hope my answer will be helpful to you.