How to remove duplicate of objects that has same value from NSArray

后端 未结 2 1954
日久生厌
日久生厌 2021-01-14 17:16

I have an NSDictinary look like this:

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


        
相关标签:
2条回答
  • 2021-01-14 18:00

    Have you try this code

    NSArray *duplicates = @[@{@"name": @"a"}, @{@"name": @"c"}, @{@"name": @"a"}, @{@"name": @"c"}, @{@"name": @"a"}];
    NSSet *set = [NSSet setWithArray:duplicates];
    NSArray *uniqueArray = [set allObjects];
    
    0 讨论(0)
  • 2021-01-14 18:04

    Just use following code for remove duplicates values.

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

    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. :)

    0 讨论(0)
提交回复
热议问题