我有一個這樣的陣列
{
OptionId = 5;
Choice Name = "Tomato"
},
{
OptionId = 1;
Choice Name = "Olives"
},
{
OptionId = 5;
ChoiceName = "Mushrooms"
},
{
OptionId = 6;
ChoiceName = "BBQ"
}
我想對這個陣列進行排序,以便結果包含 3 個元素
{
OptionId = 5
Choices = (
{
ChoiceName = "Tomato"
},
{
ChoiceName = "Mushrooms"
}
)
},
{
OptionId = 1;
Choices = (
{
Choice Name = "Olives"
)
},
{
OptionId = 6;
Choices = (
{
Choice Name = "BBQ"
)
}
}
無法得到我應該從哪里開始。任何想法/建議都會很有幫助
uj5u.com熱心網友回復:
你可以這樣做:
NSArray *initialArray = @[@{@"OptionId":@5,
@"Choice Name":@"Tomato"},
@{@"OptionId":@1,
@"Choice Name":@"Olives"
},
@{@"OptionId":@5,
@"Choice Name":@"Mushrooms"
},
@{@"OptionId":@6,
@"Choice Name":@"BBQ"
}];
NSMutableArray *finalArray = [[NSMutableArray alloc] init];
for (NSDictionary *aDictionary in initialArray) {
//We find if we already have an entry for that OptionId in the final array
NSUInteger existingIndex = [finalArray indexOfObjectPassingTest:^BOOL(NSDictionary * _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
return [obj[@"OptionId"] isEqualTo:aDictionary[@"OptionId"]];
}];
if (existingIndex != NSNotFound) {
// If we found one, we retrieve the element, and append the choice to our existing NSMutableArray
NSMutableDictionary *dict = finalArray[existingIndex];
NSMutableArray *existingArray = dict[@"Choice Name"];
[existingArray addObject:@{@"Choice Name": aDictionary[@"Choice Name"]}];
} else {
//Else we create a new entry, and we make the Choice Name an NSMutableArray, since it might have new choices afterwards
NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
dict[@"OptionId"] = aDictionary[@"OptionId"];
dict[@"Choice Name"] = [NSMutableArray arrayWithObject:@{@"Choice Name": aDictionary[@"Choice Name"]}];
[finalArray addObject:dict];
}
}
NSLog(@"Initial:\n%@", initialArray);
NSLog(@"Final:\n%@", finalArray);
輸出:
$>Initial:
(
{
"Choice Name" = Tomato;
OptionId = 5;
},
{
"Choice Name" = Olives;
OptionId = 1;
},
{
"Choice Name" = Mushrooms;
OptionId = 5;
},
{
"Choice Name" = BBQ;
OptionId = 6;
}
)
$>Final:
(
{
"Choice Name" = (
{
"Choice Name" = Tomato;
},
{
"Choice Name" = Mushrooms;
}
);
OptionId = 5;
},
{
"Choice Name" = (
{
"Choice Name" = Olives;
}
);
OptionId = 1;
},
{
"Choice Name" = (
{
"Choice Name" = BBQ;
}
);
OptionId = 6;
}
)
旁注:如果可能,請使用 custom NSObject,它會更好更容易(特別是因為鍵上的拼寫錯誤會破壞一切)。
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/463849.html
上一篇:將視窗句柄添加到在子域中運行的FileSavePickerSub
下一篇:Go模板中的浮點除法
