Question

I have array in this format

rows = [[NSArray alloc] initWithObjects:@"adam", @"alfred", @"ain", @"abdul", @"anastazja", @"angelica",
                    @"dennis" , @"deamon", @"destiny", @"dragon", @"dry", @"debug" @"drums",
                    @"Fredric", @"France", @"friends", @"family", @"fatish", @"funeral",
                    @"Mark", @"Madeline",
                    @"Nemesis", @"nemo", @"name",
                    @"Obama", @"Oprah", @"Omen", @"OMG OMG OMG", @"O-Zone", @"Ontario",
                    @"Zeus", @"Zebra", @"zed", nil];

But i need this in to following format

rows = @[@[@"adam", @"alfred", @"ain", @"abdul", @"anastazja", @"angelica"],
             @[@"dennis" , @"deamon", @"destiny", @"dragon", @"dry", @"debug", @"drums"],
             @[@"Fredric", @"France", @"friends", @"family", @"fatish", @"funeral"],
             @[@"Mark", @"Madeline"],
             @[@"Nemesis", @"nemo", @"name"],
             @[@"Obama", @"Oprah", @"Omen", @"OMG OMG OMG", @"O-Zone", @"Ontario"],
             @[@"Zeus", @"Zebra", @"zed"]];

Means that same starting character in to different dictionary

Was it helpful?

Solution

The easiest approach.

    NSArray *rows = ...;
    NSMutableDictionary *map = [NSMutableDictionary dictionary];
    for (NSString *value in rows) {
        NSString *firstLetter = [value substringToIndex:1];
        if (!map[firstLetter]) {
            map[firstLetter] = @[];
        }
        NSMutableArray *values = [map[firstLetter] mutableCopy];
        [values addObject:value];
        map[firstLetter] = values;
    }
    NSArray *finalRows = [map allValues];

Note that finalRows is not sorted.

OTHER TIPS

If you want to sort your array by it's first letter, you can try this :

NSMutableArray *outputArray = [NSMutableArray new];

NSString *lastFirstLetter = nil;
for(NSString *value in rows) {
    NSString *firstLetter = [[value substringToIndex:1] lowerString];
    if(![lastFirstLetter isEqualToString:firstLetter]) {
        lastFirstLetter = firstLetter;
        [outputArray addObject:[NSMutableArray new]];
    }
    [[outputArray lastObject] addObject:value];
} 

The idea is to iterate your input array and if the first letter of your word is different than the precedent, create a new array.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top