Filter array by first letter of string property

后端 未结 6 912
别那么骄傲
别那么骄傲 2020-12-06 05:09

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

I would like filter the array by name

    NSString          


        
6条回答
  •  失恋的感觉
    2020-12-06 05:50

    Checkout this library

    https://github.com/BadChoice/Collection

    It comes with lots of easy array functions to never write a loop again

    So you can just do

    NSArray* result = [thArray filter:^BOOL(NSString *text) {
        return [[name substr:0] isEqualToString:@"A"]; 
    }] sort];
    

    This gets only the texts that start with A sorted alphabetically

    If you are doing it with objects:

    NSArray* result = [thArray filter:^BOOL(AnObject *object) {
        return [[object.name substr:0] isEqualToString:@"A"]; 
    }] sort:@"name"];
    

提交回复
热议问题