Joshua Cleetus
Joshua Cleetus

Reputation: 672

Sorting a nsmutablearray of objects based on another array of distances

I got two nsmutablearrays one is an array of distances and another is an array containing the images linked to these distances. I need to sort the distances array in ascending order and then sort the images array based on that. I tried to make a dictionary of these 2 arrays with distance array as the key, but when the distance value is same, the same image is returned in the sorted image array. Can anyone help me with this issue. The code is as follows:

 // Put the two arrays into a dictionary as keys and values
    NSDictionary *dictionary = [NSDictionary dictionaryWithObjects:_locationImages forKeys:_distances];
    // Sort the first array
    NSArray *sortedFirstArray = [[dictionary allKeys] sortedArrayUsingComparator:^NSComparisonResult(id obj1, id obj2) {
        if ([obj1 floatValue] > [obj2 floatValue])
            return NSOrderedDescending;
        else if ([obj1 floatValue] < [obj2 floatValue])
            return NSOrderedAscending;
        return NSOrderedSame;
    }];
    // Sort the second array based on the sorted first array
    NSArray *sortedSecondArray = [dictionary objectsForKeys:sortedFirstArray notFoundMarker:[NSNull null]];           

Upvotes: 3

Views: 1581

Answers (2)

Mundi
Mundi

Reputation: 80273

You do not need the distance as the key. Just have an array of dictionaries. Somehow this also makes it easier to sort.

NSMutableArray *dataArray = [NSMutableArray array];
for (int i=0; i<distanceArray.count; i++) {
    [dataArray addObject:@{
       @"distance" : distanceArray[i],
       @"image"    : imageArray[i]
    }];
}
NSArray *sorted = [dataArray sortedArrayUsingDescriptors:@[
                   [NSSortDescriptor sortDescriptorWithKey:@"distance"
                                                 ascending:YES]]];

Upvotes: 8

Sebastian
Sebastian

Reputation: 7720

You could combine both arrays into one array of dictionaries

arrayElement[@"distance"] = @(someDistance);
arrayElement[@"image"] = someImage;

then sort the array.

Upvotes: 0

Related Questions