简体   繁体   English

如何按字母顺序对数组排序

[英]How to sort an array in alphabetical order

I have 2 NSMutableArray array. 我有2个NSMutableArray数组。 First array is storing UserID and second array is storing related UserName. 第一个数组存储UserID,第二个数组存储相关的UserName。 Here is dummy structure of arrays. 这是数组的虚拟结构。

First array= {"1","5","2","8"}; 第一个数组= {“ 1”,“ 5”,“ 2”,“ 8”}; Second array={"Akash", "Martin", "Hui", "Ajay"}; 第二个数组= {“ Akash”,“ Martin”,“ Hui”,“ Ajay”};

I want to sort Second in alphabetical order but respected UserID also should be sort. 我想按字母顺序对Second进行排序,但尊敬的UserID也应进行排序。

You should use NSDictionary for this task. 您应该将NSDictionary用于此任务。 Your sorting process will be easier then. 这样您的排序过程将变得更加容易。 You can use key value pair mechanism of NSDictionary like key is ID and value is name. 您可以使用NSDictionary的键值对机制,例如键是ID,值是名称。

Duplicate of this question. 这个问题重复。

This is how you do it, if anArray is your start array: 如果anArray是您的起始数组,这是您的方法:

sortedArray = [anArray sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];

Also, you should use NSDictionary for this, that way when it's sorted, both the keys and values are sorted the same. 同样,您应该为此使用NSDictionary,这样,在对它进行排序时,键和值都将进行相同的排序。

If there is no duplicated UserName in the second array, you could: 1. create a Map 2. put UserName array and UserID array to the Map with UserName -> UserID 3. sort the second array, the default order is alphabatical order. 如果第二个数组中没有重复的UserName,则可以:1.创建一个Map 2.使用UserName-> UserID将UserName数组和UserID数组放入Map中。3.排序第二个数组,默认顺序为字母顺序。 4. sequentially access each element in the second array and get the related UserID from the map and rearrange the first array. 4.顺序访问第二个数组中的每个元素,并从映射中获取相关的UserID并重新排列第一个数组。

I think this link can help you, take a look at this; 我认为此链接可以为您提供帮助,请看一下;

How to sort an NSMutableArray with custom objects in it? 如何排序带有自定义对象的NSMutableArray?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM