我这里有两个不同的数组
[
"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 dateFromStringbj1];
NSDate *date2 = [dateFormatter dateFromStringbj2];
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
]
你能建议我如何解决这个问题吗? 谢谢。
一种方法是向原始数组添加索引并对其进行排序,以及字符串数据...
// 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 dateFromStringbj1[0]];
NSDate *date2 = [dateFormatter dateFromStringbj2[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 所需的结果。
关于ios - 获取数组上对象的索引而不重复,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39751391/
欢迎光临 OStack程序员社区-中国程序员成长平台 (https://ostack.cn/) | Powered by Discuz! X3.4 |