Search code examples
objective-csortingnsarraygrouping

Sorting and Grouping NSArray into new NSMutablearray


I have a NSMutableDictionary *dict that contains a NSArray with key kfoo. I would like to rebuild the array with its contents to get them into new groups. How could I achieve this?

2013-12-16 06:28:14.236 weather[1246:303] {
    kfoo =     (
                (
            AAAAA,
            11111,
            sun
        ),
                (
            BBBBB,
            22222,
            mond
        ),
                (
            CCCCC,
            33333,
            sun
        ),
                (
            DDDDD,
            44444,
            water
        )
    );
}

From this log above, this is what I would like to have:

2013-12-16 06:28:14.236 weather[1246:303] {
    kfoo =     (
            sun =(
            AAAAA,
            11111,
            CCCCC,
            33333
        ),
            mond =(
            BBBBB,
            22222
        ),
            water =(
            DDDDD,
            44444
        )
    );
}

Solution

  • How about something like this? This assumes your key name is always at index 2 (ideally you should find a more robust way to determine your key). You'd need to pass kfoo into it.

    - (NSMutableDictionary *) processWeatherArray:(NSArray *)toProcess {
        NSMutableDictionary *toReturn = [NSMutableDictionary dictionary];
    
        for(NSArray *array in toProcess)
        {
            NSString *key = array[2];
            if ([toReturn objectForKey:key] == nil) {
                [toReturn setObject:[NSMutableArray array] forKey:key];
            }
            NSMutableArray *keyValue = [toReturn objectForKey:key];
    
            for(int i=0; i<array.count; i++)
            {
                if (array[i] != key)
                {
                    [keyValue addObject:array[i]];
                }
            }
        }
        return toReturn;
    }