这是我的方法,时间复杂度稍好一些。第一个函数convertDataBasedOnKey
将接收您可能想要比较的值,正如您在想要通过 key 搜索的问题上所说的那样。第二个函数getSharedDictionaryOfElements
仅用于创建具有合并值的最终字典。
- (void)convertDataBasedOnKey:(NSString *)baseKey {
desiredFormatData = [[NSMutableArray alloc] init];
NSMutableString *filterString = [NSMutableString stringWithFormat:@"(%@ ==",baseKey];
[filterString appendString:@" %@)"];
while (currentFormatData.count != 0) {
NSDictionary *aDictionary = [currentFormatData firstObject];
NSString *firstValue = [aDictionary objectForKey:baseKey];
NSArray *filtered = [currentFormatData filteredArrayUsingPredicate:
[NSPredicate predicateWithFormat:filterString, firstValue]];
NSDictionary *mergedDictionary = [self getSharedDictionaryOfElements:filtered sharingValueForKey:baseKey];
[desiredFormatData addObject:mergedDictionary];
[currentFormatData removeObjectsInArray:filtered];
}
NSLog(@"%@",desiredFormatData.description);
}
- (NSDictionary *)getSharedDictionaryOfElements:(NSArray *)anArray sharingValueForKey:(NSString *)aKey {
if (!anArray || anArray.count == 0) {
return nil;
}
// As all the elements in anArray share the same keys
NSMutableDictionary *resultDictionary = [[NSMutableDictionary alloc] init];
NSDictionary *modelDictionary = [anArray firstObject];
for (NSString *aKey in modelDictionary.allKeys) {
NSPredicate *filterByKey = [NSPredicate predicateWithValue:YES];
NSArray *resultArray = [[anArray valueForKey:aKey] filteredArrayUsingPredicate:filterByKey];
NSMutableArray *uniqueArray = [NSMutableArray arrayWithArray:[[NSSet setWithArray:resultArray] allObjects]];
[resultDictionary setObject:uniqueArray forKey:aKey];
}
return resultDictionary;
}
例子
使用这两个函数来获得你所问的将是这样的:
声明了这两个变量后:
NSMutableArray *currentFormatData;
NSMutableArray *desiredFormatData;
然后用示例数据填充第一个并基于键“汽车”进行操作:
currentFormatData = [NSMutableArray arrayWithArray:@[@{@"car":@"Ferrari", @"make":@"Italian", @"color":@"red"},
@{@"car":@"Ferrari", @"make":@"Italian", @"color":@"yellow"},
@{@"car":@"Porsche", @"make":@"German", @"color":@"green"},
@{@"car":@"Porsche", @"make":@"German", @"color":@"silver"}]];
[self convertDataBasedOnKey:@"car"];