0

How would I filter through an array and return values that contain a certain part of a string? I have a text box where, for the sake of this example, a user puts in 25, and then hits a "Done" button.

Example:

Original Array {25-1002, 25-1005, 12-1003, 1000-0942, 1-1, 234-25}

I want it to return (after sorting through it and pulling the values I want):

New Array {25-1002, 25-1005}

Please note that in the original array, the last value of 234-25 has a 25 in it as well but is not pulled through. It needs to be the number on the first part of the hyphen.

Thanks in advance!

pgb
  • 24,813
  • 12
  • 83
  • 113
Baub
  • 5,004
  • 14
  • 56
  • 99
  • 1
    A similar answer is here: http://stackoverflow.com/questions/110332/filtering-nsarray-into-a-new-nsarray-in-objective-c – pgb Aug 16 '11 at 19:29

2 Answers2

3

Use the -filteredArrayUsingPredicate: method, like this:

NSString *searchText = [someField.text stringByAppendingString:@"-"];
newArray = [originalArray filteredArrayUsingPredicate:[NSPredicate predicateWithBlock:^(NSString *value, NSDictionary *bindings){
    return ([value rangeOfString:searchText].location != NSNotFound)
}]];

Note that blocks (the ^{} thing) aren’t available pre-iOS 4, so you’ll have to use another of NSPredicate’s constructors if you’re targeting 3.x devices as well.

Noah Witherspoon
  • 57,021
  • 16
  • 130
  • 131
1

as an easy to understand answer (not using NSPredicate, which can be intimidating (but is really the correct way to do it)):

NSMutableArray *myNewArray = [[NSMutableArray alloc] init];
for (NSString *string in myArray) {
    if([[string substringToIndex:3] isEqualToString @"25-"])
    {
        [myNewArray addObject:string];
    }
}
Jesse Naugher
  • 9,780
  • 1
  • 41
  • 56