1

Suppose I would like to sort array by "firstName" key.

Example

Array = (
   {
     People1 = {
         firstName = @"Jack Adam";
         email = @"adam@gmail.com";
     };
     Address = {
         cityCode = @"TH";
     };
   },
     People2 = {
         firstName = @"Jack DAm";
         email = @"dam@gmail.com";
     };
      Address = {
         city = @"TH";
     };
);
Popeye
  • 11,839
  • 9
  • 58
  • 91
Dashzaki
  • 568
  • 2
  • 6
  • 13

5 Answers5

2

user Sort Comparator

NSArray *sortedArray = [unsortedArray sortedArrayUsingComparator:^(NSDictionary *a, NSDictionary *b) {

  return [a[@"People"][@"firstname"] compare:b[@"People"][@"firstname"]];

}];

But Your Key is inconsistency ... I Think that data should be

Array = (
{
 People = {
     firstName = @"Jack Adam";
     email = @"adam@gmail.com";
 };
 Address = {
     cityCode = @"TH";
 };
},
 People = {
     firstName = @"Jack DAm";
     email = @"dam@gmail.com";
 };
  Address = {
     city = @"TH";
 };
);
Kiattisak Anoochitarom
  • 2,157
  • 1
  • 20
  • 15
0

First,you should implement a compare-method for your object.

- (NSComparisonResult)compare:(Person *)otherObject {
    return [self.birthDate compare:otherObject.birthDate];
}

NSArray *sortedArray;
sortedArray = [drinkDetails sortedArrayUsingSelector:@selector(compare:)];
Bug
  • 2,576
  • 2
  • 21
  • 36
hackcat
  • 19
  • 2
0

Using blocks and modern Objective-C syntax:

NSArray *sortedArray = [unsortedArray sortedArrayUsingComparator:^(NSDictionary *first, NSDictionary *second) {

      return [first[@"Person"] compare:second[@"Person"]];

}];
sergio
  • 68,819
  • 11
  • 102
  • 123
0

Using NSSortDescriptor:

NSSortDescriptor *descriptor = [[NSSortDescriptor alloc] initWithKey:@"firstName"  ascending:YES];
    myArray=[stories sortedArrayUsingDescriptors:[NSArray arrayWithObjects:descriptor,nil]];
    temp = [stories copy]; //temp is NSMutableArray

myArray is the array you want to sort.

Nikos M.
  • 13,685
  • 4
  • 47
  • 61
0

As you replied in a comment, the first dictionary key is "Person1" in all array elements. Then "Person1.firstName" is the key path that gives the first name of each array element. This key path can be used in a sort descriptor:

NSArray *array = ... // your array
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"Person1.firstName" ascending:YES];
NSArray *sortedArray = [array sortedArrayUsingDescriptors:@[sort]];
Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382