如何从NSArray中删除具有相同值的对象的重复项 [英] How to remove duplicate of objects that has same value from NSArray

查看:104
本文介绍了如何从NSArray中删除具有相同值的对象的重复项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NSDictinary看起来像这样:

I have an NSDictinary look like this:

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

如何删除具有相同名称的词典.例如,我要删除重复的"a"和"c".我希望结果是这样的:

How to remove the ditionaries which have the same name. For example, I want to remove the duplicate "a" and "c". I want the result to be like this:

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

推荐答案

只需使用以下代码删除重复值即可.

Just use following code for remove duplicates values.

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

您只需使用键名调用groupsWithDuplicatesRemoved此方法.

You have to just call groupsWithDuplicatesRemoved this method with key name.

- (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;
}

希望,这就是您想要的.如有任何疑问,请联系我. :)

Hope, this is what you're looking for. Any concern get back to me. :)

这篇关于如何从NSArray中删除具有相同值的对象的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆