将两个 NSArray 并排排序 [英] Sorting two NSArrays together side by side

查看:29
本文介绍了将两个 NSArray 并排排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有几个需要并排排序的数组.

I have several arrays that need to be sorted side by side.

例如,第一个数组有名称:@[@"Joe"、@"Anna"、@"Michael"、@"Kim"],以及另一个数组保存地址:@[@"Hollywood bld", @"Some street 3", @"that other street", @"country road"],数组的索引放在一起.乔"住在好莱坞大厦"等等.

For example, the first array has names: @[@"Joe", @"Anna", @"Michael", @"Kim"], and and the other array holds addresses: @[@"Hollywood bld", @"Some street 3", @"That other street", @"country road"], where the arrays' indexes go together. "Joe" lives at "Hollywood bld" and so on.

我想按字母顺序对名称数组进行排序,然后将地址数组排列在一起,以便它们仍然在一起,Hollywood bld"与Joe"具有相同的索引.我知道如何使用

I would like to sort the names array alphabetically, and then have the address array sorted alongside so they still go together, with "Hollywood bld" having same index as "Joe". I know how to sort one array alphabetical with

NSSortDescriptor *sort=[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:NO];
[myArray sortUsingDescriptors:[NSArray arrayWithObject:sort]];

但是有没有什么简单的方法可以使用适当的顺序对第二个数组进行排序?

But is there any easy way of getting the second array sorted using the appropriate order?

推荐答案

  1. 创建一个置换数组,初始设置为p[i]=i
  2. 根据第一个数组的name键对排列进行排序
  3. 使用置换对两个数组重新排序

示例:假设第一个数组是 {"quick", "brown", "fox"}.排列从 {0, 1, 2} 开始,排序后变成 {1, 2, 0} .现在您可以遍历排列数组,并根据需要对原始数组和第二个数组重新排序.

Example: let's say the first array is {"quick", "brown", "fox"}. The permutation starts as {0, 1, 2}, and becomes {1, 2, 0} after the sort. Now you can go through the permutation array, and re-order the original array and the second array as needed.

NSArray *first = [NSArray arrayWithObjects: @"quick", @"brown", @"fox", @"jumps", nil];
NSArray *second = [NSArray arrayWithObjects: @"jack", @"loves", @"my", @"sphinx", nil];
NSMutableArray *p = [NSMutableArray arrayWithCapacity:first.count];
for (NSUInteger i = 0 ; i != first.count ; i++) {
    [p addObject:[NSNumber numberWithInteger:i]];
}
[p sortWithOptions:0 usingComparator:^NSComparisonResult(id obj1, id obj2) {
    // Modify this to use [first objectAtIndex:[obj1 intValue]].name property
    NSString *lhs = [first objectAtIndex:[obj1 intValue]];
    // Same goes for the next line: use the name
    NSString *rhs = [first objectAtIndex:[obj2 intValue]];
    return [lhs compare:rhs];
}];
NSMutableArray *sortedFirst = [NSMutableArray arrayWithCapacity:first.count];
NSMutableArray *sortedSecond = [NSMutableArray arrayWithCapacity:first.count];
[p enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    NSUInteger pos = [obj intValue];
    [sortedFirst addObject:[first objectAtIndex:pos]];
    [sortedSecond addObject:[second objectAtIndex:pos]];
}];
NSLog(@"%@", sortedFirst);
NSLog(@"%@", sortedSecond);

这篇关于将两个 NSArray 并排排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆