我在这里有两个不同的阵列
LinearLayout
我正在使用以上两个数组进行排序,如下面的代码
bottom
排序第二个数组后,
[
"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)
一种方法是将索引添加到原始数组并对其进行排序,以及字符串数据......
// 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);
输出如下:
Start sortedTimes= (
(
"21:55",
0
),
(
"21:55",
1
),
(
"21:55",
2
),
(
"21:55",
4
),
(
"22:00",
3
)
)
运行该数组以拾取已排序的结果和已排序的索引...
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);
经过测试以匹配OP所需的结果。