I've an two different arrays here
[
"21:55",
"21:55",
"21:55",
"22:00",
"21:55"
]
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm"];
NSArray *sortedTimes = [timeArraySorting sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2)
{
NSDate *date1 = [dateFormatter dateFromString:obj1];
NSDate *date2 = [dateFormatter dateFromString:obj2];
return [date1 compare:date2];
}];
NSLog(@"Start sortedTimes= %@",sortedTimes);
sortedTimes = [
"21:55",
"21:55",
"21:55",
"21:55",
"22:00"
]
[
0,
0,
0,
0,
3
]
[
0,
1,
2,
4,
3
]
One way is to add indexes to the original array and sort those too, along with the string data...
// data from the OP
NSArray *timeArraySorting = @[
@"21:55",
@"21:55",
@"21:55",
@"22:00",
@"21:55"
];
// add index data to it, so it has the form:
// @[ [ @"21:55", @0], [ @"21:55", @1], ...
NSMutableArray *indexedTimeArray = [@[] mutableCopy];
for (int i=0; i<timeArraySorting.count; i++) {
[indexedTimeArray addObject: @[timeArraySorting[i], @(i)] ];
}
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"HH:mm"];
// sort that indexed data
NSArray *sortedTimes = [indexedTimeArray sortedArrayUsingComparator:^NSComparisonResult(NSArray *obj1, NSArray *obj2) {
NSDate *date1 = [dateFormatter dateFromString:obj1[0]];
NSDate *date2 = [dateFormatter dateFromString:obj2[0]];
return [date1 compare:date2];
}];
NSLog(@"Start sortedTimes= %@",sortedTimes);
Output looks like this:
Start sortedTimes= (
(
"21:55",
0
),
(
"21:55",
1
),
(
"21:55",
2
),
(
"21:55",
4
),
(
"22:00",
3
)
)
Run through that array to pickup the sorted result and the sorted indexes...
NSMutableArray *result = [@[] mutableCopy];
NSMutableArray *indexes = [@[] mutableCopy];
for (NSArray *a in sortedTimes) {
[result addObject:a[0]];
[indexes addObject:a[1]];
}
NSLog(@"result is %@", result);
NSLog(@"indexes is %@", indexes);
Tested to match the OP desired result.