-1

Say I have an array of 6 dictionaries- each dictionary has a "location" key with it's associated value. How can i sort those values together so i could go from this...

"location" : USA
"location" : UK
"location" : Asia
"location" : UK
"location" : USA
"location" : Asia

to this?

"location" : Asia
"location" : Asia
"location" : UK
"location" : UK
"location" : USA
"location" : USA
Gman9855
  • 477
  • 5
  • 17
  • It is impossible to sort key-value pair inside NSDictionary. The only way - loop through NSDictionary and store pairs somewhere, – Avt Mar 06 '14 at 18:53

1 Answers1

0

I guess sortedArrayUsingComparator: method is what you are looking for:

NSArray *array = @[@{@"location" : @"USA"},
                   @{@"location" : @"UK"},
                   @{@"location" : @"Asia"},
                   @{@"location" : @"UK"},
                   @{@"location" : @"USA"},
                   @{@"location" : @"Asia"}];
NSArray *sortedArray = [array sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    return [[obj1 valueForKey:@"location"] compare:[obj2 valueForKey:@"location"]];
}];
dariaa
  • 6,285
  • 4
  • 42
  • 58