V. Garg V. Garg - 4 months ago 10
iOS Question

how to remove duplicates from array of dictionary for a specific key

{
distance = "0.03159804520191554";
rid = 374824705969;
uuid = "1838346268_374823983610_2016-08-08T07:32:08.679GMT";
},
{

rid = 374824705969;
uuid = "1838346268_374823983610_2016-08-08T07:32:08.679GMT";
},
{
rid = 374824706065;
uuid = "1838346268_374823983610_2016-08-08T07:32:22.680GMT";
}


This is what I got from the array of dictionaries. I want to remove duplicates where rid=374824705969 without using loops.Can any one help me.
Thanks in advance.

Answer

Try these one:

NSArray *array = @[
    @{
        @"rid" : @374824705969,
        @"uuid" : @"1838346268_374823983610_2016-08-08T07:32:08.679GMT"
    },
    @{
        @"rid" : @374824705969,
        @"uuid" : @"1838346268_374823983610_2016-08-08T07:32:08.679GMT"
    },
    @{
        @"rid" : @374824706065,
        @"uuid" : @"1838346268_374823983610_2016-08-08T07:32:22.680GMT"
    }];


    NSMutableSet *keys = [NSMutableSet new];
    NSMutableArray *result = [NSMutableArray new];

    for (NSDictionary *data in array) {
        NSString *key = data[@"rid"];
        if ([keys containsObject:key]) {
            continue;
        }

        [keys addObject:key];
        [result addObject:data];
    }

NSLog(@"%@", result);