0
    {
        "restaurant name" : "str1",
         "distance": 19.4
    }
    {
        "restaurant name" : "str2",
         "distance": 2.1
    {
        "restaurant name" : "str3",
         "distance":19.3
    }
    {
        "restaurant name" : "str4",
         "distance": 2.1
    }

Above is my array of dictionary values restaurant name and key. I have used following code but it is not sorting properly. It is showing sequence 19.3 ,19.4, 2.1, 2.1. I think it is comparing only first digit

NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:kRestaurantListDistance ascending:YES selector:@selector(compare:)];
[restaurantList sortUsingDescriptors:[NSArray arrayWithObjects:sortDescriptor, nil]];

Please tell me proper code to sort out array in ascending order.

3 Answers 3

1

You can maybe try this :

array = [[NSMutableArray alloc] initWithArray:[array sortedArrayUsingComparator:^(id obj1, id obj2) {
    float distance1 = [[obj1 objectForKey:@"distance"] floatValue];
    float distance2 = [[obj2 objectForKey:@"distance"] floatValue];

    if (distance1 < distance2) {
        return (NSComparisonResult)NSOrderedDescending;
    } else if (distance1 > distance2) {
        return (NSComparisonResult)NSOrderedAscending;
    } else {
        return (NSComparisonResult)NSOrderedSame;
    }
}]];
Sign up to request clarification or add additional context in comments.

Comments

0

If it's sorting by the first digit, that means that your numbers are, in fact, just strings.

Two possible approaches:

  1. Before you sort then, convert them to numbers (it's in a dictionary, so they'll have to be NSNumbers rather than simple floats)
  2. Create your own compare method or block (I typically prefer to use initWithKey:ascending:comparator:)

Which approach you use depends on what you do with the dictionary afterwards. If you need numbers again later, 1 is probably best; otherwise 2.

Comments

0

You can maybe try this. it will work :

arrWholeArrImg=[NSMutableArray sortArray:_arrWholeArrImg string:@"CategoryName"];

    +(NSMutableArray *)sortArray:(NSMutableArray *)arr  string:(NSString *)key {
   NSSortDescriptor *sortDescriptor;
   sortDescriptor = [[NSSortDescriptor alloc] initWithKey:key
                                                       ascending:YES];
   NSArray *sortDescriptors = [NSArray arrayWithObject:sortDescriptor];
   NSArray  *sortedArray = [arr sortedArrayUsingDescriptors:sortDescriptors];
                    arr = [sortedArray mutableCopy];
                    return arr;
    } 

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.