Reputation: 871
I want to filter an array of arrays using another array which is a subset of these arrays.
NSMutableArray* y = [NSMutableArray arrayWithObjects:@"A",@"B", nil];
NSArray *array = @[
@[@"A", @"B", @"C"],
@[@"A", @"B", @"E"],
@[@"A", @"B", @"D"],
@[@"B", @"C", @"D"],
];
I want to filter the second array such that it contains the items which has both "A" and "B" in it.
I used the predicate:
NSPredicate *intersectPredicate =[NSPredicate predicateWithFormat:@"ANY SELF IN %@", y];
NSArray *intersect = [array filteredArrayUsingPredicate:intersectPredicate];
But this gives me all the items in second Array. I think ANY/SOME is considering (A || B) I want to have (A && B). I tried ALL but it gives nothing.
Upvotes: 1
Views: 1135
Reputation: 4656
Any/Some would give all the arrays which contain either A or B.
All would give all the arrays which have just 2 elements A & B.
By defining a custom predicate we can get the desired results:
NSPredicate *intersectPredicate = [NSPredicate predicateWithBlock:^BOOL(id evaluatedObject, NSDictionary *bindings) {
for (NSString *str in y) {
if (![evaluatedObject containsObject:str]) {
return false;
}
}
return true;
}];
NSArray *intersect = [array filteredArrayUsingPredicate:intersectPredicate];
Upvotes: 3