从字典数组中删除键值的重复项 [英] Removing duplicates of a key value from an array of dictionaries

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

问题描述

我正在做一个Facebook API请求,要求我返回特定Facebook群组中所有相册的名称。我找回了一个包含3个键/值的字典数组,其中一个是映射到专辑名称的键'name',以及键'id'和'created_time'。

I am doing a Facebook API request to give me back all the names of the albums from a particular Facebook group. I get back an array of dictionaries with 3 keys/values, one of which being the key 'name' which maps to the album name, along with the keys 'id' and 'created_time'.

唯一的问题是,由于某种原因,我正在找回专辑的重复名称值...但只有一对。当我进入Facebook页面时,无论如何只有一个该专辑的实例,没有重复。

Only problem is that for some reason i'm getting back duplicate 'name' values of albums... but only a couple. And when i go to the Facebook page there's only one instance of that album anyway, no duplicates.

此外,他们的'id'值不同,但它只是重复组中的第一个字典,其具有实际指向有效数据的Facebook ID,另一个Facebook id值只是在你用它们执行Facebook图形搜索时不返回任何内容,所以它是我想要的第一个重复项。

Also, their 'id' values are different, but it's only the first dictionary from the group of duplicates that has a Facebook id that actually points to valid data, the other Facebook id values just don't return anything when you perform a Facebook graph search with them, so it's the first of the duplicates that i want.

我如何删除这些我的数组中无用的重复词典,并保持一个有效的Facebook ID?谢谢! :)

How can i remove these useless duplicate dictionaries from my array and keep the one with a valid Facebook id?? Thanks! :)

推荐答案

首先,我想说找一个获得'清洁'清单的方法可能更有利来自faceBook,而不是事后掩盖问题。这可能是不可能的,但至少要找出这种行为的原因或提交错误报告。

First I'd like to say that it's probably more beneficial to find a way to get a 'clean' list from faceBook as opposed to covering up problems afterwards. This might not be possible right now, but at least find out what the reason is for this behaviour or file a bug report.

除此之外,这应该可行:

Barring that, this should do the trick:

-(NSMutableArray *) groupsWithDuplicatesRemoved:(NSArray *)  groups {
    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 =[group objectForKey:@"name"]; //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;
}

这篇关于从字典数组中删除键值的重复项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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