Search code examples
iosobjective-cnsarraynspredicatensset

2 NSArrays, find intersection based on a property value?


I have 2 NSArrays of 2 different types of custom objects.

Object A properties: ID: Name: Author:

Object B Properties: bookID: value: terminator:

I need to filter an array of objects of type "A" that has the ID value equal to the bookID value of any of the objects of the second array that contains objects of type "B".

I tried to use the intersectSet: method by converting the arrays to sets, but since both the objects are of different type, nothing happened.

What will be the most efficient way to do the filtering? Can I specify the properties to look when I am doing an intersect?


Solution

  • Here is a sample code with example:

    NSDictionary *dictionaryA1 = @{@"ID":@"1", @"Name":@"NameA1", @"Author":@"AuthorA1"};
    NSDictionary *dictionaryA2 = @{@"ID":@"2", @"Name":@"NameA2", @"Author":@"AuthorA2"};
    NSDictionary *dictionaryA3 = @{@"ID":@"3", @"Name":@"NameA3", @"Author":@"AuthorA3"};
    
    NSDictionary *dictionaryB0 = @{@"bookID":@"0", @"Name":@"NameB0", @"Author":@"AuthorB0"};
    NSDictionary *dictionaryB1 = @{@"bookID":@"1", @"Name":@"NameB1", @"Author":@"AuthorB1"};
    NSDictionary *dictionaryB3 = @{@"bookID":@"3", @"Name":@"NameB3", @"Author":@"AuthorB3"};
    
    NSArray *arrayA = @[dictionaryA1, dictionaryA2, dictionaryA3];
    NSArray *arrayB = @[dictionaryB0, dictionaryB1, dictionaryB3];
    
    NSArray *intersectionWithBookID = [arrayA filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"ID IN %@", [arrayB valueForKey:@"bookID"]]];
    
    NSLog(@"intersectionWithBookID: %@", intersectionWithBookID);
    

    Output:

    intersectionWithBookID: (
            {
            Author = AuthorA1;
            ID = 1;
            Name = NameA1;
        },
            {
            Author = AuthorA3;
            ID = 3;
            Name = NameA3;
        }