【问题标题】:How to remove duplicate of objects that has same value from NSArray如何从 NSArray 中删除具有相同值的对象的重复项
【发布时间】:2016-10-26 16:40:11
【问题描述】:

我的NSDictinary 看起来像这样:

NSArray *duplicates = @[@{@"name": @"a", @"id": @"123"}, @{@"name": @"c", @"id": @"234"}, @{@"name": @"a", @"id": @"431"}, @{@"name": @"c", @"id": @"983"}, @{@"name": @"a", @"038"}];

如何删除同名的词典。例如,我想删除重复的“a”和“c”。我希望结果是这样的:

NSArray *duplicates = @[@{@"name": @"a", @"id": @"123"}, @{@"name": @"c", @"id": @"234"}];

【问题讨论】:

标签: ios objective-c


【解决方案1】:

只需使用以下代码删除重复值。

your_array = [self groupsWithDuplicatesRemoved:(NSArray *)your_array myKeyParameter:@"your_key_name"];

你只需要用键名调用groupsWithDuplicatesRemoved这个方法。

- (NSMutableArray *) groupsWithDuplicatesRemoved:(NSArray *)  groups myKeyParameter:(NSString *)myKeyParameter {
    NSMutableArray * groupsFiltered = [[NSMutableArray alloc] init];    //This will be the array of groups you need
    NSMutableArray * groupNamesEncountered = [[NSMutableArray alloc] init]; //This is an array of group names seen so far

    NSString * name;        //Preallocation of group name
    for (NSDictionary * group in groups) {  //Iterate through all groups
        name = [NSString stringWithFormat:@"%@", [group objectForKey:myKeyParameter]]; //Get the group name
        if ([groupNamesEncountered indexOfObject: name]==NSNotFound) {  //Check if this group name hasn't been encountered before
            [groupNamesEncountered addObject:name]; //Now you've encountered it, so add it to the list of encountered names
            [groupsFiltered addObject:group];   //And add the group to the list, as this is the first time it's encountered
        }
    }
    return groupsFiltered;
}

希望,这就是您要找的。任何问题都可以回复我。 :)

【讨论】:

  • 如果你有多个键进入一个字典并且所有数据进入一个数组。现在您只想根据一个键获得唯一的数组。那你一定要用这个技巧。
  • 比如你有一个这样的数组..NSArray *duplicates = @[@{@"name": @"a", @"name1": @"c"}, @{@"name": @"b", @"name1": @"d"}, @{@"name": @"c", @"name1": @"d"}, @{@"name": @"d"}, @{@"name1": @"d"}];...现在你想根据"name1"键得到唯一的数组..那个时候你必须要用这个这样的代码...unique_array = [self groupsWithDuplicatesRemoved:(NSArray *)duplicates myKeyParameter:@"name1"];
【解决方案2】:

你试过这个代码吗

NSArray *duplicates = @[@{@"name": @"a"}, @{@"name": @"c"}, @{@"name": @"a"}, @{@"name": @"c"}, @{@"name": @"a"}];
NSSet *set = [NSSet setWithArray:duplicates];
NSArray *uniqueArray = [set allObjects];

【讨论】:

  • 不好意思提一下,每个字典都有id,但是id都是唯一的。所以你的方法行不通,我想。请查看更新的问题。
  • @yongho 我明白了。你不是以前数组中的豪宅ID。
猜你喜欢
  • 2021-10-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-03-02
  • 2018-12-07
  • 2020-07-15
  • 2020-07-22
相关资源
最近更新 更多