1

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.

1
  • Well, it's really only considering the y array in this case because that's the search term you've given the NSPredicate for. Commented Aug 16, 2014 at 8:45

1 Answer 1

3

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];
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.