Oguz Ulgen
Oguz Ulgen

Reputation: 35

Objective-C Sorting an Array by the values of an inner Array

I want to sort a NSMutableArray which has NSArrays with respect to the value at the index 1 of the NSArray. I'll try to draw a picture of arrays.

NSMutableArray *ultimateHighscoreArray = { 
    ( (NSString) userName, (double) score, (int) numOfCorrectAnswers ) , 
      ( John , 4.5 , 3 ) , 
      ( Terry , 7.5 , 1) , 
                                     ... }

The first array within the NSMutableArray is an example which shows how examples are located. Second and third are how the values actually are. So, what I want is to sort these arrays having the array containing higher value at first index to go higher up in the ranking. For this example the array that has 7.5 which is Terry Array should go before the one that has 4.5 . I want the results to be held in a NSMutableArray in decreasing order. Thank you.

Upvotes: 1

Views: 400

Answers (3)

omz
omz

Reputation: 53561

The sortUsingComparator: method allows you to sort an array using a block, e.g.:

[ultimateHighscoreArray sortUsingComparator:^(id obj1, id obj2) {
    return [[obj1 objectAtIndex:1] compare:[obj2 objectAtIndex:1]];
}];

For clarity, it would probably be better to use an array of dictionaries (or instances of a custom class) for this data structure.

Upvotes: 2

Ole Begemann
Ole Begemann

Reputation: 135578

This should do it:

[ultimateHighscoreArray sortUsingComparator:^(id obj1, id obj2) {
    NSNumber *score1 = [obj1 objectAtIndex:1];
    NSNumber *score2 = [obj2 objectAtIndex:2];

    // Reverse the comparison here (compare score2 to score1)
    // in order to get a descending order
    return [score2 compare:score1];
}];

A general advice: your data structure would be clearer if it were an array of NSDictionary instances or even an array of custom objects (e.g., your custom Score class). In those cases, you could also use NSSortDescriptor to sort the array, which would result in cleaner, easier-to-read code.

Upvotes: 2

Ryan Poolos
Ryan Poolos

Reputation: 18561

You can write a custom comparator like this :)

[ultimateHighscoreArray sortUsingComparator:^NSComparisonResult(id obj1, id obj2) {
    NSArray *arrayA = (NSArray *)obj1;
    NSArray *arrayB = (NSArray *)obj2;

    double scoreA = [arrayA objectAtIndex:1];
    double scoreB = [arrayB objectAtIndex:1];

    if (scoreA > scoreB) {
        return NSOrderedDescending;
    } else if (scoreA < scoreB) {
        return NSOrderedAscending;
    } else {
        return NSOrderedSame;
    }
}];

Upvotes: 0

Related Questions