Search code examples
iosobjective-cnsarray

Sort multi dimensional array based on sum of internal arrays in objective c


Let's say I have a multi-dimensional array like this:

(
    (2, 2, 1),
    (0, 1, 2),
    (0, 1, 1),
    (0, 0, 1),
    (0, 0, 2),
    (0, 1, 3),
    (0, 1, 0),
    (0, 0, 1),
    (0, 0, 1),
    (1, 3, 3)
)

Now I need to sort this array in descending order of the internal array's sum.

I tried by adding this array and another array of the sum values in a dictionary, but it doesn't work if the sum contains similar numbers.

i.e, I want the result to be:

(1, 3, 3),
(2, 2, 1),
(0, 1, 3),
(0, 1, 2),
(0, 1, 1),
(0, 0, 2),
(0, 0, 1),
(0, 0, 1),
(0, 1, 0)

Any help would be appreciated!


Solution

  • You can do that with key-value coding:

    NSArray *array = …; // Whatever you have
    
    NSSortDescriptor *sorter = [NSSortDescriptor sortDescriptorWithKey:@"@sum.self" ascending:NO]; // @sum is an aggregate
    NSArray *sorted = [array sortedArrayUsingDescriptors:@[sorter]]);