简体   繁体   中英

How to sort an array in alphabetical order

I have 2 NSMutableArray array. First array is storing UserID and second array is storing related UserName. Here is dummy structure of arrays.

First array= {"1","5","2","8"}; Second array={"Akash", "Martin", "Hui", "Ajay"};

I want to sort Second in alphabetical order but respected UserID also should be sort.

You should use NSDictionary for this task. Your sorting process will be easier then. You can use key value pair mechanism of NSDictionary like key is ID and value is name.

Duplicate of this question.

This is how you do it, if anArray is your start array:

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.

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. 4. sequentially access each element in the second array and get the related UserID from the map and rearrange the first array.

I think this link can help you, take a look at this;

How to sort an NSMutableArray with custom objects in it?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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