Search code examples
iosiphonearraysnsset

Subtracting the array, Regarding key in dictionary


I have two array let's say

NSArray *array1=@[ @{@"key1":@"A",@"key2":@"AA"},@{@"key1":@"C",@"key2":@"CC"},@{@"key1":@"E",@"key2":@"EE"},@{@"key1":@"G",@"key2":@"GG"}];
NSArray *array2=@[ @{@"key1":@"A",@"key2":@"AAA"},@{@"key1":@"Z",@"key2":@"ZZZ"}];

I want to subtract the array, This should be the expected reuslt,

NSArray *resultArray=@[ @{@"key1":@"C",@"key2":@"CC"},@{@"key1":@"E",@"key2":@"EE"},@{@"key1":@"G",@"key2":@"GG"}];

I tried the below code but didn't working

NSArray *extracted = [array1 valueForKey:@"key1"];
NSMutableSet *pressieContactsSet = [NSMutableSet setWithArray:extracted];
NSMutableSet *allContactSet = [NSMutableSet setWithArray:array2];

[allContactSet minusSet:pressieContactsSet];

NSLog(@"%@",allContactSet);

Solution

  • Please try below code

    First get all key1 objects in temporary array. Then apply filter on array1 and check if your array1 object contain arrayKey1 object.

    Make sure it will only check for key1 key.

    NSArray *arrKey1 = [array2 valueForKey:@"key1"];
    NSPredicate *pred = [NSPredicate predicateWithBlock:
                                ^BOOL(id evaluatedObject, NSDictionary *bindings)
                                {
                                    if ([arrKey1 containsObject:evaluatedObject[@"key1"]])
                                    {
                                        NSLog(@"found : %@",evaluatedObject);
                                        return NO;
                                    }
                                    else
                                    {
                                        NSLog(@"Not found : %@",evaluatedObject);
                                        return YES;
                                    }
    
                                }];
    NSArray *arrSubtracted = [array1 filteredArrayUsingPredicate:pred];
    
    NSLog(@"%@", arrSubtracted);
    

    Or you can use enumerateObjectsUsingBlock

    NSMutableArray *resultArray = [NSMutableArray new];
    
    [array1 enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop)
    {
        if (![arrKey1 containsObject:obj[@"key1"]]) {
            [resultArray addObject:obj];
        }
    }];
    NSLog(@"%@",resultArray);
    

    Hope this will help you.