Using NSPredicate to filter array of arrays

DanielR picture DanielR · Jun 21, 2013 · Viewed 16.2k times · Source

I have the following situation:

NSArray(
    NSArray(
        string1,
        string2,
        string3,
        string4,
        string5,
    )
    ,
    NSArray(
        string6,
        string7,
        string8,
        string9,
        string10,
   )
)

Now I need a predicate that returns the array that contains a specific string. e.g. Filter Array that contains string9 -> I should get back the entire second array because I need to process the other strings inside that array. Any ideas?

Answer

Martin R picture Martin R · Jun 21, 2013

Just for completeness: It can be done using predicateWithFormat::

NSArray *array = @[
    @[@"A", @"B", @"C"],
    @[@"D", @"E", @"F"],
];

NSString *searchTerm = @"E";
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"ANY SELF == %@", searchTerm];
NSArray *filtered = [array filteredArrayUsingPredicate:predicate];
NSLog(@"%@", filtered);

Output:

(
    (
        D,
        E,
        F
    )
)