Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filter array by first letter of string property

I have an NSArray with objects that have a name property.

I would like filter the array by name

    NSString *alphabet = [agencyIndex objectAtIndex:indexPath.section];
    //---get all states beginning with the letter---
    NSPredicate *predicate =
    [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", alphabet];
    NSMutableArray *listSimpl = [[NSMutableArray alloc] init];
    for (int i=0; i<[[Database sharedDatabase].agents count]; i++) {
        Town *_town = [[Database sharedDatabase].agents objectAtIndex:i];
        [listSimpl addObject:_town];
    }
    NSArray *states = [listSimpl filteredArrayUsingPredicate:predicate];

But I get an error - "Can't do a substring operation with something that isn't a string (lhs = <1, Arrow> rhs = A)"

How can I do this? I would like to filter the array for the first letter in name being 'A'.

like image 351
Nubaslon Avatar asked Sep 10 '13 08:09

Nubaslon


People also ask

How do you filter a string array?

To filter strings of an Array based on length in JavaScript, call Array. filter() method on this String Array, and pass a function as argument that returns true for the specific condition on string length or false otherwise.

How do you filter items in an array?

One can use filter() function in JavaScript to filter the object array based on attributes. The filter() function will return a new array containing all the array elements that pass the given condition. If no elements pass the condition it returns an empty array.

Can you use filter on a string?

You can't use filter() on a string as it is an Array.


1 Answers

Try with following code

NSPredicate *pred = [NSPredicate predicateWithFormat:@"SELF like %@", yourName];
NSArray *filteredArr = [yourArray filteredArrayUsingPredicate:pred];

EDITED :

NSPredicate pattern should be:

NSPredicate *pred =[NSPredicate predicateWithFormat:@"name beginswith[c] %@", alphabet];
like image 178
iPatel Avatar answered Sep 28 '22 03:09

iPatel