所以如果你有你的字典数组:
NSArray *originalArray = @[
@{@"code": @1, @"category":@"drink"},
@{@"code": @2, @"category":@"drink"},
@{@"code": @3, @"category":@"drink"},
@{@"code": @4, @"category":@"food"},
@{@"code": @5, @"category":@"food"},
@{@"code": @6, @"category":@"drink"}
];
您可以通过以下方式获得所需的内容:
NSMutableArray *arrayOfCategories = [NSMutableArray array];
NSMutableArray *arrayOfArrayOfCodes = [NSMutableArray array];
for (NSDictionary *originalArrayEntry in originalArray)
{
NSString *category = originalArrayEntry[@"category"];
NSString *code = originalArrayEntry[@"code"];
NSInteger indexInArrayOfCategories = [arrayOfCategories indexOfObject:category];
NSMutableArray *arrayOfCodes;
if (indexInArrayOfCategories == NSNotFound)
{
indexInArrayOfCategories = [arrayOfCategories count];
arrayOfCodes = [NSMutableArray array];
[arrayOfArrayOfCodes addObject:arrayOfCodes];
[arrayOfCategories addObject:category];
}
else
{
arrayOfCodes = arrayOfArrayOfCodes[indexInArrayOfCategories];
}
[arrayOfCodes addObject:code];
}
NSLog(@"arrayOfArrayOfCodes = %@", arrayOfArrayOfCodes);
NSLog(@"arrayOfCategories = %@", arrayOfCategories);
请注意,您没有要求类别值数组,但我认为您要求的结果集在没有它的情况下毫无意义。
就个人而言,如果我想完成您的要求(并消除对单独数组的需要)并且顺序并不重要,我可能会倾向于使用具有代码数组值的字典(由类别值键入),例如,源于:
NSMutableDictionary *resultDictionary = [NSMutableDictionary dictionary];
for (NSDictionary *originalArrayEntry in originalArray)
{
NSString *category = originalArrayEntry[@"category"];
NSString *code = originalArrayEntry[@"code"];
NSMutableArray *arrayForCategory = resultDictionary[category];
if (!arrayForCategory)
{
arrayForCategory = [NSMutableArray array];
resultDictionary[category] = arrayForCategory;
}
[arrayForCategory addObject:code];
}
NSLog(@"resultDictionary = %@", resultDictionary);