views:

42

answers:

2

If I have an NSArray (or mutable array) with several dictionary objects (each dictionary is a Person) like this:

[
  { forename: chris, surname: smith, age: 22 }
  { forename: paul, surname: smith, age: 24 }
  { forename: dave, surname: jones, age: 21 }
  { forename: alan, surname: jones, age: 26 }
  { forename: cecil, surname: reeves, age: 32 }
  { forename: pablo, surname: sanchez, age: 42 }
]

How would I separate it into an array of four arrays, sorted by surname (and within that forename), like so:

[
    [ 
      { forename: alan, surname: jones, age: 26 }
      { forename: dave, surname: jones, age: 21 }
    ]
    [  
      { forename: cecil, surname: reeves, age: 32 }
    ]
    [
      { forename: pablo, surname: sanchez, age: 42 }
    ]
    [ 
      { forename: chris, surname: smith, age: 22 }
      { forename: paul, surname: smith, age: 24 }
    ]
]
+2  A: 

You should use a specialized Person class, instead of an NSDictionary.


You could first group it into Dictionary of Arrays of Dictionaries, e.g.

NSMutableDictionary* result = [NSMutableDictionary dictionary];
for (Person* person in peopleArray) {
    NSString* surname = person.surname;
    NSMutableArray* surnameArray = [result objectForKey:surname];
    if (surnameArray == nil) {
        [result setObject:[NSMutableArray arrayWithObject:person]
                   forKey:surname]; 
    } else {
        [surnameArray addObject:person];
    }
}
return result;

You could use [result allValues] if you really need an Array.

If you need a sorted array, you need to sort it manually:

NSArray* sortedSurnames = [[result allKeys] sortedArrayUsingSelector:@selector(compare:)];
return [result objectsForKeys:sortedSurnames notFoundMarker:[NSNull null]];
KennyTM
+4  A: 

You can do some pretty neat stuff using key-value coding and predicates...

//retrieve an array of the distinct surnames
NSArray * distinctSurnames = [peopleArray valueForKeyPath:@"@distinctUnionOfObjects.surname"];
//at this point, if you need the surnames in a specific order, you can do so here.

NSMutableArray * groupedPeople = [NSMutableArray array];

//for each of the surnames...
for (NSString * surname in distinctSurnames) {
  //create a predicate to only find people with this surname
  NSPredicate * filter = [NSPredicate predicateWithFormat:@"surname = %@", surname];
  //retrieve only the people with this surname and add them to the final array
  [groupedPeople addObject:[peopleArray filteredArrayUsingPredicate:filter]];
}

This will work for either a Person object (which would be better) or dictionaries, as long as the dictionaries have a @"surname" key or the Person object has a -(NSString *)surname method.

Dave DeLong
Awesome solution! Not enough people use KVC. Really slick.
Jonathan Sterling