You can achieve what you want by following these steps:
- Create an empty but mutable dictionary.
- Get the first character.
- If the key for this symbol does not exist, create it.
- Add the word to the key value (must be NSMutableArray).
- Repeat step # 2 for all keys.
Here is the Objective-C code for these steps. Please note that I assume that you want the keys to be insensitive .
// create our dummy dataset NSArray * wordArray = [NSArray arrayWithObjects:@"Apple", @"Pickle", @"Monkey", @"Taco", @"arsenal", @"punch", @"twitch", @"mushy", nil]; // setup a dictionary NSMutableDictionary * wordDictionary = [[NSMutableDictionary alloc] init]; for (NSString * word in wordArray) { // remove uppercaseString if you wish to keys case sensitive. NSString * letter = [[word substringWithRange:NSMakeRange(0, 1)] uppercaseString]; NSMutableArray * array = [wordDictionary objectForKey:letter]; if (!array) { // the key doesn't exist, so we will create it. [wordDictionary setObject:(array = [NSMutableArray array]) forKey:letter]; } [array addObject:word]; } NSLog(@"Word dictionary: %@", wordDictionary);
source share