以与另一个数组相同的顺序对一个数组进行排序

编程入门 行业动态 更新时间:2024-10-11 13:31:08
本文介绍了以与另一个数组相同的顺序对一个数组进行排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

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

更多推荐

以与另一个数组相同的顺序对一个数组进行排序

本文发布于:2023-11-29 04:09:42,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1645226.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:数组   顺序

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!