How can I get an array of the indexes from another array that has been sorted?
I want to sort an array by its objets and then get the indexes like so:
NSMutableArray *myAr开发者_Python百科ray = [[NSMutableArray alloc] initWithObjects: @"3", @"2", @"1", @"0", @"1", @"2", nil];
I want the indexes of the objects in ascending order. Here, because the lowest value has an index of 3, the indexes would be would be: 3, 2, 4, 1, 5, 0 or something like that.
Any ideas?
Thanks!
Here's what I ended up doing:
//Create a mutable array of the indexes in the myArray (just a list from 0...n)
NSMutableArray *indexes = [[NSMutableArray alloc] init];
for (int i = 0; i < myArray.count; i++){
[indexes addObject: [NSNumber numberWithInteger:i]];
}
//Create a dictionary with myArray as the objects and the indexes as the keys
NSDictionary *tempDictionary = [NSDictionary dictionaryWithObjects:myArray forKeys:indexes];
//Create an array of myArray's keys, in the order they would be in if they were sorted by the values
NSArray *sorted = [tempDictionary keysSortedByValueUsingSelector: @selector(compare:)];
just sort it and use indexOfObject:
. Like so:
NSArray *sorted = [myArray sortedArrayUsingSelector: @selector(compare:)];
NSMutableArray *indices = [NSMutableArray array];
for (id object in myArray)
[indices addObject: [NSNumber numberWithInteger: [sorted indexOfObject: object]]];
(Out of my head, hope this works.)
You can also use below of the code, May its useful to you,
NSSortDescriptor *_lastDescriptor = [[NSSortDescriptor alloc] initWithKey:@"" ascending:YES];
NSArray *_lastArray = [NSArray arrayWithObject:_lastDescriptor];
firstCharacterArray = (NSMutableArray *)[[nameIndexesDictionary allKeys] sortedArrayUsingDescriptors:_lastArray];
//firstCharacterArray = (NSMutableArray *)[[nameIndexesDictionary allKeys] sortedArrayUsingSelector:@selector(localizedCaseInsensitiveCompare:)];
for (NSString *eachlastIndex in firstCharacterArray)
{
NSSortDescriptor *lastDescriptor = [[NSSortDescriptor alloc] initWithKey:@""
ascending:YES];
//selector:@selector(localizedCaseInsensitiveCompare:)] ;
NSArray *descriptorslast = [NSArray arrayWithObject:lastDescriptor];
[[nameIndexesDictionary objectForKey:eachlastIndex] sortUsingDescriptors:descriptorslast];
[lastDescriptor release];
}
精彩评论