ios - 获取数组上对象的索引而不重复
<p><p>我这里有两个不同的数组</p>
<pre><code> [
"21:55",
"21:55",
"21:55",
"22:00",
"21:55"
]
</code></pre>
<p>我正在使用上面的两个数组来排序如下代码,</p>
<pre><code> NSDateFormatter *dateFormatter = [ init];
;
NSArray *sortedTimes = [timeArraySorting sortedArrayUsingComparator:^NSComparisonResult(NSString *obj1, NSString *obj2)
{
NSDate *date1 = ;
NSDate *date2 = ;
return ;
}];
NSLog(@"Start sortedTimes= %@",sortedTimes);
</code></pre>
<p>像这样对第二个数组进行排序后,</p>
<pre><code>sortedTimes = [
"21:55",
"21:55",
"21:55",
"21:55",
"22:00"
]
</code></pre>
<p>但我需要将第二个数组与第一个数组进行比较以获取第一个数组的索引。但在这里我得到这样的重复项,</p>
<pre><code>[
0,
0,
0,
0,
3
]
</code></pre>
<p>但我需要这样,</p>
<pre><code>[
0,
1,
2,
4,
3
]
</code></pre>
<p>你能建议我如何解决这个问题吗?
谢谢。</p></p>
<br><hr><h1><strong>Best Answer-推荐答案</ strong></h1><br>
<p><p>一种方法是向原始数组添加索引并对其进行排序,以及字符串数据...</p>
<pre><code>// 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++) {
, @(i)] ];
}
NSDateFormatter *dateFormatter = [ init];
;
// sort that indexed data
NSArray *sortedTimes = [indexedTimeArray sortedArrayUsingComparator:^NSComparisonResult(NSArray *obj1, NSArray *obj2) {
NSDate *date1 = ];
NSDate *date2 = ];
return ;
}];
NSLog(@"Start sortedTimes= %@",sortedTimes);
</code></pre>
<p>输出如下所示:</p>
<pre><code>Start sortedTimes= (
(
"21:55",
0
),
(
"21:55",
1
),
(
"21:55",
2
),
(
"21:55",
4
),
(
"22:00",
3
)
)
</code></pre>
<p>遍历该数组以获取排序结果和排序索引...</p>
<pre><code>NSMutableArray *result = [@[] mutableCopy];
NSMutableArray *indexes = [@[] mutableCopy];
for (NSArray *a in sortedTimes) {
];
];
}
NSLog(@"result is %@", result);
NSLog(@"indexes is %@", indexes);
</code></pre>
<p>经过测试以匹配 OP 所需的结果。</p></p>
<p style="font-size: 20px;">关于ios - 获取数组上对象的索引而不重复,我们在Stack Overflow上找到一个类似的问题:
<a href="https://stackoverflow.com/questions/39751391/" rel="noreferrer noopener nofollow" style="color: red;">
https://stackoverflow.com/questions/39751391/
</a>
</p>
页:
[1]