Bangalore
Bangalore

Reputation: 1580

How to get last element from NSMutableArray in which status as complete?

I have an array of dictionaries in following format

[
{
 "status":"not completed",
 "rating":2 
},{
"status":"completed",
 "rating":2 
},{
"status":"not completed",
"rating":"<null>" 
},{
 "status":"completed",
 "rating":"<null>"},{
"status":"not completed",
"rating":"<null>" 
}
]

and from this i want response as last object where status is completed and rating is null

output
{
     "status":"completed",
     "rating":"<null>"
}

how do i get second element easily without any big iteration.

in real case this array might contains 150-300 elements.

  -(void)checkRecentUnratedOrder:(NSMutableArray *)order{

    NSLog(@"trip log - %@",[order valueForKey:@"status"]); // total 5 objects inside array in that 4 of them are completed

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.status == completed"];
    NSArray *arr = [order filteredArrayUsingPredicate:predicate];

    NSLog(@"trip arr%@",arr);




}

console enter image description here

Upvotes: 1

Views: 367

Answers (1)

Nirav D
Nirav D

Reputation: 72430

You need to predicate your array like this

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"self.status == 'completed'"];
NSArray *arr = [order filteredArrayUsingPredicate:predicate];
// Now `arr` contains all the `dictionary` that `status` key contain `completed` value. 

Upvotes: 1

Related Questions