-1

I'm having a two dimensional array as follows

NSArray *cities = [NSArray arrayWithObjects:@"New Delhi",@"Karachi",@"Dhaka",@"Columbu", nil];
NSArray *distance = [NSArray arrayWithObjects:@"500",@"1400",@"1200",@"2800", nil];
NSMutableArray *details= [[NSMutableArray alloc]initWithCapacity:cities.count];
[details addObject:cities];
[details addObject:distance];

Now, the details array looks like

(
    (
    "New Delhi",
    Karachi,
    Dhaka,
    Columbu
 ),
    (
    500,
    1400,
    1200,
    2800
 )
)

I need to sort the array with ascending order w.r.t distance array ie,

(
    (
    "New Delhi",
    Dhaka,
    Karachi,
    Columbu
 ),
    (
    500,
    1200,
    1400,
    2800
 )
)

how to do this?

I also need to sort the whole array by alphabetical order w.r.t cities array.

I tried using sortUsingComparator but, can't get the solution completely.

Any help would be appreciated.

2

2 Answers 2

1
self.arrayForRows = [[NSMutableArray alloc]init];
NSMutableArray *arrayForCities = [[NSMutableArray alloc]initWithObjects:@"Mumbai",@"Vizag",@"Hyderabad",@"Ahemdabad",@"Secunderabad", nil];
    NSMutableArray *arrayForDistance = [[NSMutableArray alloc]initWithObjects:@"200",@"320",@"32",@"450",@"14", nil];

    for (int i=0; i<arrayForCities.count; i++)
    {
        NSMutableDictionary *tempDicts = [[NSMutableDictionary alloc]init];
        [tempDicts setObject:[arrayForCities objectAtIndex:i] forKey:@"names"];
        [tempDicts setObject:[NSNumber numberWithInt:[[arrayForDistance objectAtIndex:i] intValue]] forKey:@"distance"];
        [self.arrayForRows addObject:tempDicts];
    }

    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"distance" ascending:YES];
    [self.arrayForRows sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];
Sign up to request clarification or add additional context in comments.

2 Comments

It's a coincidence that both of our answers are very same.
I changed the sortdescriptor initwithkey to names object, it sorts the array with alphabatical order too. much needed help, thx again
1

Structure is complicated. Make a class city containing name and distance. Then add objects of this class. Then you can sort using city.distance.

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.