Sorting nsmutablearray objects based on another distance array

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

 // 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]];           

      

+3


source to share


2 answers


You don't need distance as a key. Just use an array of dictionaries. Somehow it also makes sorting easier.



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]]];

      

+8


source


You can combine both arrays into one array of dictionaries

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

      



then sort the array.

0


source







All Articles