Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 272
NSF Avatar asked Dec 12 '22 03:12

NSF


2 Answers

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;
    }
like image 162
Larme Avatar answered Jan 14 '23 14:01

Larme


I m hopping your 2 NSArrays are like

arrayA = ( ObjectA1, ObjectA2, . . ObjectAn )

and

arrayB = ( ObjectB1, ObjectB2, . . ObjectBn )

In this case you have to first extract the values into separate arrays using predicate like this for both arrayA and arrayB

NSPredicate *predicateA = [NSPredicate predicateWithFormat:@"id"];
NSArray *arrayAWithonlyIds = [arrayA filteredArrayUsingPredicate:predicateA];

NSPredicate *predicateB = [NSPredicate predicateWithFormat:@"bookId"];
NSArray *arrayBWithonlyBookIds = [arrayA filteredArrayUsingPredicate:predicateB];

Now you have to convert these result array containing only ids to NSSet inorder to perform set operation like intersection like this

NSMutableset *setResult = [NSMutableSet setWithArray: arrayAWithonlyIds];
[setResult intersectSet:[NSSet setWithArray: arrayBWithonlyBookIds]];

I hope this gives you an Idea.

like image 23
Srinivasan N Avatar answered Jan 14 '23 12:01

Srinivasan N