我想从nsmutablearray中删除重复项。
数组结构: -
( { "act_end_date" = ""; "act_entry_date" = "13/11/2014"; "act_recurrrance_type" = Daily; "act_start_date" = "2014-11-13"; "row_id" = 0; "act_id" = 2; } { "act_end_date" = ""; "act_entry_date" = "13/11/2014"; "act_recurrrance_type" = Daily; "act_start_date" = "2014-11-13"; "row_id" = 1; "act_id" = 2; } { "act_end_date" = ""; "act_entry_date" = "16/11/2014"; "act_recurrrance_type" = Daily1; "act_start_date" = "2014-11-15"; "row_id" = 2; "act_id" = 3; } )
我想要的是检查数组包含任何具有相同act_id的字典。 如果是,则删除第一个字典。 即上述数组的预期结果: -
(
{
"act_end_date" = "";
"act_entry_date" = "13/11/2014";
"act_recurrrance_type" = Daily;
"act_start_date" = "2014-11-13";
"row_id" = 1;
"act_id" = 2;
}
{
"act_end_date" = "";
"act_entry_date" = "16/11/2014";
"act_recurrrance_type" = Daily1;
"act_start_date" = "2014-11-15";
"row_id" = 2;
"act_id" = 3;
}
)
他们有什么办法吗? 是否可以使用NSPREDICATE?
我试图用以下方式做到: -
NSMutableArray *filteredArray = [NSMutableArray array];
for (NSMutableDictionary* E1 in Event_Array)
{
BOOL hasDuplicate = [[filteredArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"act_id == %@", [E1 objectForKey:@"act_id"]]] count] > 0;
if (!hasDuplicate)
{
[filteredArray addObject:E1];
}
}
因为它返回数组:---
(
{
"act_end_date" = "";
"act_entry_date" = "13/11/2014";
"act_recurrrance_type" = Daily;
"act_start_date" = "2014-11-13";
"row_id" = 0;
"act_id" = 2;
}
)
我想要的是
(
{
"act_end_date" = "";
"act_entry_date" = "13/11/2014";
"act_recurrrance_type" = Daily;
"act_start_date" = "2014-11-13";
"row_id" = 1;
"act_id" = 2;
}
)
答案 0 :(得分:5)
NSMutableSet *keysSet = [[NSMutableSet alloc] init];
NSMutableArray *filteredArray = [[NSMutableArray alloc]init];
for (NSDictionary *msg in germanMakes) {
NSString *key = [NSString stringWithFormat:@"%@", msg[@"act_id"]];
if (![keysSet containsObject:key]) {
[filteredArray addObject:msg];
[keysSet addObject:key];
}
}
NSLog(@"filteredResults %@ keyset%@",filteredArray , keysSet);
germanMakes是你的初始数组,keysSet包含唯一的act_id(例如1,2,3,4 ..),filteredArray是由act_id过滤的数组。请记住,这不会按升序排序,但这部分很容易。
答案 1 :(得分:2)
假设您希望最新的对象位于列表中。
解决方案1:(简单)
反转你的数组
NSMutableArray *filteredArray = [NSMutableArray array];
for (int i = Event_Array.count-1; i>= 0; i--)
{
NSMutableDictionary* E1 = [Event_Array objectAtIndex:i];
BOOL hasDuplicate = [[filteredArray filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"act_id == %@", [E1 objectForKey:@"act_id"]]] count] > 0;
if (!hasDuplicate)
{
[filteredArray addObject:E1];
}
}
解决方案2:
使用NSMutableDictionary而不是数组。
//Keys are act_id(s) "2" = { "act_end_date" = ""; "act_entry_date" = "13/11/2014"; "act_recurrrance_type" = Daily; "act_start_date" = "2014-11-13"; "row_id" = 1; "act_id" = 2; }; "3" = { "act_end_date" = ""; "act_entry_date" = "16/11/2014"; "act_recurrrance_type" = Daily1; "act_start_date" = "2014-11-15"; "row_id" = 2; "act_id" = 3; }