1

I have an NSArray called myArray. I want to filter myArray objects so, that I exclude all elements from this array corresponding to the keywords from another array keywords.

So, that's my pseudocode:

keywords = @[@"one", @"three"];
myArray = @[@"textzero", @"textone", @"texttwo", @"textthree", @"textfour"];
predicate = [NSPredicate predicateWithFormat:@"NOT (SELF CONTAINS_ANY_OF[cd] %@), keywords];
myArray = [myArray filteredArrayUsingPredicate:predicate];

And that's what I want to get by NSLog(@"%@", myArray)

>> ("textzero", "texttwo", "textfour")

How should I do it?

Artem E.
  • 23
  • 5

2 Answers2

0

Use this code:

NSArray *keywords = @[@"one", @"three"];
NSArray *myArray = @[@"textzero", @"textone", @"texttwo", @"textthree", @"textfour"];
NSString * string = [NSString stringWithFormat:@"NOT SELF CONTAINS[c] '%@'", [keywords componentsJoinedByString:@"' AND NOT SELF CONTAINS[c] '"]];
NSPredicate* predicate = [NSPredicate predicateWithFormat:string];
NSArray* filteredData = [myArray filteredArrayUsingPredicate:predicate];
NSLog(@"Complete array %@", filteredData);
0

You can use a block to filter the array. Usually a block is faster.

keywords = @[@"one", @"three"];
myArray = @[@"textzero", @"textone", @"texttwo", @"textthree", @"textfour"];
predicate = [NSPredicate predicateWithBlock:^(NSString *evaluatedObject, NSDictionary<NSString *,id> *bindings){
    for (NSString *key in keywords)
        if ([evaluatedObject rangeOfString:key options:NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch].location != NSNotFound)
            return NO;
    return YES;
}];
myArray = [myArray filteredArrayUsingPredicate:predicate];

or

keywords = @[@"one", @"three"];
myArray = @[@"textzero", @"textone", @"texttwo", @"textthree", @"textfour"];
NSIndexSet *indices = [myArray indexesOfObjectsPassingTest:^(NSString *obj, NSUInteger idx, BOOL *stop){
    for (NSString *key in keywords)
        if ([obj rangeOfString:key options:NSCaseInsensitiveSearch | NSDiacriticInsensitiveSearch].location != NSNotFound)
            return NO;
    return YES;
}];
myArray = [myArray objectsAtIndexes:indices];
Willeke
  • 14,578
  • 4
  • 19
  • 47