我有这样的NSMutableArray:
// NSMutableArray *Data = (NSMUtableArray(NSDictionary))
Data = {"Device": "A1", "Temperature": "25", "datetime": "2013.02.03"},
{"Device": "A2", "Temperature": "25", "datetime": "2013.02.03"},
{"Device": "A3", "Temperature": "25", "datetime": "2013.02.03"},
{"Device": "A1", "Temperature": "25", "datetime": "2013.02.04"},
{"Device": "A2", "Temperature": "25", "datetime": "2013.02.04"}.
我如何按照“日期时间”细分并将其分组到单独的NSMutableArray中。如上情况将分为:
Data_d1 = {"Device": "A1", "Temperature": "25", "datetime": "2013.02.03"},
{"Device": "A2", "Temperature": "25", "datetime": "2013.02.03"},
{"Device": "A3", "Temperature": "25", "datetime": "2013.02.03"}
和
Data_d2 = {"Device": "A1", "Temperature": "25", "datetime": "2013.02.04"},
{"Device": "A2", "Temperature": "25", "datetime": "2013.02.04"}
最佳答案
如果您有这样的字典数组数组:
var data = [["Device": "A1", "Temperature": "25", "datetime": "2013.02.02"],
["Device": "A2", "Temperature": "25", "datetime": "2013.02.03"],
["Device": "A3", "Temperature": "25", "datetime": "2013.02.03"],
["Device": "A1", "Temperature": "25", "datetime": "2013.02.04"],
["Device": "A2", "Temperature": "25", "datetime": "2013.02.04"]]
然后,您可以根据以下任何键将它们隔离:
var dateArray = data.compactMap{ $0["datetime"] }
let uDateArray = Array(Set(dateArray))
var segregatedArray = [[[String: String]]]()
for dateTime in uDateArray {
segregatedArray.append(data.filter{$0["datetime"] == dateTime})
}
print(segregatedArray);
根据要求添加带有字典数组作为原始数据的Objective-C版本。
考虑您有如下的字典数组:
NSArray *array=@[
@{@"Device": @"A1",@"Temperature":@"25",@"datetime":@"2013.02.03"},
@{@"Device":@"A2",@"Temperature":@"25",@"datetime":@"2013.02.03"},
@{@"Device":@"A3",@"Temperature":@"25",@"datetime":@"2013.02.03"},
@{@"Device":@"A1",@"Temperature":@"25",@"datetime":@"2013.02.04"},
@{@"Device":@"X1",@"Temperature":@"26",@"datetime":@"2013.02.07"},
@{@"Device":@"Y1",@"Temperature":@"27",@"datetime":@"2013.02.07"},
@{@"Device":@"A2",@"Temperature":@"25",@"datetime":@"2013.02.04"}];
然后,您可以按以下方式将它们隔离:
NSMutableDictionary* mutableDic = [[NSMutableDictionary alloc] initWithCapacity:1];
for (NSDictionary* dic in array) {
NSString* dateTime = [dic valueForKey:@"datetime"];
NSMutableArray* data = [mutableDic valueForKey:dateTime];
if(data != nil)//data with this key avalaibe, add further.
{
[data addObject:dic];
}
else//data with this key not avalaibe, make a mutable array with this dic and add.
{
NSMutableArray* newData = [[NSMutableArray alloc] initWithObjects:dic, nil];
[mutableDic setValue:newData forKey:dateTime];
}
}
NSLog(@"%@", mutableDic);
您可以根据任何密钥进行隔离,只需将该密钥放在
[dic valueForKey:@"datetime"];
即可。您可以按注释要求输入datetime
代替Device
。隔离后调试器的屏幕截图: