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;
}
}
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]];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With