1

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

Bangalore
  • 1,572
  • 4
  • 20
  • 50
  • Start at the end of the array and iterate backwards. As soon as you find an element with a "status" of "completed", return it. – user94559 Jul 16 '16 at 06:44

1 Answers1

1

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. 
Nirav D
  • 71,513
  • 12
  • 161
  • 183