以与另一个数组相同的顺序对一个数组进行排序 [英] Sorting one array in the same order as another array

查看:714
本文介绍了以与另一个数组相同的顺序对一个数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个数组。让我们说:

I have two arrays. Let's say:

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

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 是我的 IQ 变量。我使用 sortBack 数组以相同的顺序重新排列另一个数组。

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;
    }
}


推荐答案

这将是为用户制作字典的更好方法。然后根据IQ,Name等特定值进行排序。

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]];

这篇关于以与另一个数组相同的顺序对一个数组进行排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆