Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting one array in the same order as another array

Tags:

sorting

xcode

ios

I have two arrays. Let's say:

array = "Dave", "Mike", "Joe", "Jason", "Kevin"

and

IQ = 110, 145, 75, 122, 130

I want to sort them by IQ. Say Highest to lowest. I can sort one array... and then I go back and check to see what position it was in and then rearrange the other array. It seems like there must be a better way to do this. Especially if the array gets larger.

Here is how I'm doing it right now.

d1, d2, d3, d4, d5 are my IQ variable. I use the sortBack array to rearrange another array in the same order.

NSMutableArray *myArray = [NSMutableArray arrayWithObjects:[NSString stringWithFormat:@"%d",d1], [NSString stringWithFormat:@"%d",d2],[NSString stringWithFormat:@"%d",d3], [NSString stringWithFormat:@"%d",d4],[NSString stringWithFormat:@"%d",d5], nil];

//sorting
[myArray sortUsingComparator:^NSComparisonResult(NSString *str1, NSString *str2) {
    return [str1 compare:str2 options:(NSNumericSearch)];
}];

for(int i=0;i<5;i++)
{
    if([[myArray objectAtIndex:i] integerValue]==d1)
    {
        sortBackArray[i]=1;
    }
    else if([[myArray objectAtIndex:i] integerValue]==d2)
    {
        sortBackArray[i]=2;
    }
    else if([[myArray objectAtIndex:i] integerValue]==d3)
    {
        sortBackArray[i]=3;
    }
    else if([[myArray objectAtIndex:i] integerValue]==d4)
    {
        sortBackArray[i]=4;
    }
    else if([[myArray objectAtIndex:i] integerValue]==d5)
    {
        sortBackArray[i]=5;
    }
}
like image 648
Cherr Skees Avatar asked May 23 '13 09:05

Cherr Skees


1 Answers

This would be a better way to make a dictionary for users. And then sorting based on their specific values like IQ, Name etc.

NSArray *users = @[@"Dave",@"Mike",@"Joe",@"Jason",@"Kevin"];
NSArray *iqs = @[@110,@145,@75,@122,@130];

NSMutableArray *array = [NSMutableArray array];
for (int idx = 0;idx<[users count];idx++) {
    NSDictionary *dict = @{@"Name": users[idx],@"IQ":iqs[idx]};
    [array addObject:dict];
}

NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"IQ" ascending:NO];
[array sortUsingDescriptors:@[descriptor]];
like image 113
Anupdas Avatar answered Oct 17 '22 00:10

Anupdas