Anand
Anand

Reputation: 1129

Sort 2D NSMutableArray

I have 2D array Like following:

NSMutableArray *world=[[NSMutableArray alloc]init];
NSNumber *number;
NSMutableArray *inner;

int scr=2;
number=[[NSNumber alloc]initWithInt:scr];
inner=[[NSMutableArray alloc]initWithObjects:@"ABC",number,nil];
[world addObject:inner];

scr=6;
number=[[NSNumber alloc]initWithInt:scr];
inner=[[NSMutableArray alloc]initWithObjects:@"XYZ",number,nil];
[world addObject:inner];

scr=1;
number=[[NSNumber alloc]initWithInt:scr];
inner=[[NSMutableArray alloc]initWithObjects:@"PQR",number,nil];
[world addObject:inner];

scr=5;
number=[[NSNumber alloc]initWithInt:scr];
inner=[[NSMutableArray alloc]initWithObjects:@"DEF",number,nil];
[world addObject:inner];

scr=3;
number=[[NSNumber alloc]initWithInt:scr];
inner=[[NSMutableArray alloc]initWithObjects:@"LMN",number,nil];
[world addObject:inner];

Now,I want to Sort the world array to have following result,

XYZ 6
DEF 5
LMN 3
ABC 2
PQR 1

can anybody please help me, Thanks in advance...

Upvotes: 2

Views: 544

Answers (1)

Hailei
Hailei

Reputation: 42153

You can use sortedArrayUsingComparator: to sort the array by customized sorting code block. Have a try with this:

NSArray *sortedWorld = [world sortedArrayUsingComparator:^(id a, id b) {
    NSNumber *numA = [a objectAtIndex:1];
    NSNumber *numB = [b objectAtIndex:1];
    return [numB compare:numA];
}];

Upvotes: 6

Related Questions