Removing duplicates of a key value from an array of dictionaries

我是研究僧i 提交于 2019-12-21 18:44:09

问题


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'.

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.

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.

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


回答1:


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


来源:https://stackoverflow.com/questions/24820376/removing-duplicates-of-a-key-value-from-an-array-of-dictionaries

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!