Consider a simple NSObject subclass called Object with two properties: name and group.

I need to produce from an NSArray of Objects, an NSArray of NSArrays, each subarray containing objects sorted by name and all having the same group value. The output array must be sorted by group.

What are some concise and efficient ways to do this?

Example:

Input:

@[
    @{ @"name" : @"E", @"group" : @"Y" },
    @{ @"name" : @"D", @"group" : @"Z" },
    @{ @"name" : @"B", @"group" : @"Y" },
    @{ @"name" : @"C", @"group" : @"X" },
    @{ @"name" : @"D", @"group" : @"Z" },
    @{ @"name" : @"A", @"group" : @"X" },
    @{ @"name" : @"F", @"group" : @"X" },
    @{ @"name" : @"G", @"group" : @"Y" },
}]

Output:

@[
    @[
        @{ @"name" : @"A", @"group" : @"X" },
        @{ @"name" : @"C", @"group" : @"X" },
        @{ @"name" : @"F", @"group" : @"X" },
    ],
    @[
        @{ @"name" : @"B", @"group" : @"Y" },
        @{ @"name" : @"E", @"group" : @"Y" },
        @{ @"name" : @"G", @"group" : @"Y" },
    ],
    @[
        @{ @"name" : @"D", @"group" : @"Z" },
    ],
]
有帮助吗?

解决方案

If a dictionary of arrays would work...

NSMutableDictionary *groupedDictionary = [NSMutableDictionary dictionary];

for (Object *anObject in originalArray) {
    NSMutableArray *groupArray = [groupedDictionary objectForKey:anObject.group];

    if(groupArray) {
        [groupArray addObject:anObject];
    } else {
        groupArray = [NSMutableArray arrayWithObject:anObject];
        [groupedDictionary addObject:groupArray forKey:anObject.group];
    }
}

The result is a dictionary of arrays. The key is the group, the value is the array of objects in that group.

If you still need it as an array, you can actually then turn this dictionary into an array by doing this:

NSArray *groupedArrays = [groupedDictionary allValues];
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top