如何用另一个 NSArray 对 NSArray 进行排序?

How to sort a NSArray with another NSArray?

NSArray A = @[[[@"id":@"3"]], [[@"id":@"4"]] ,[[@"id":@"c"]],[[@"id":@"f"]]];
NSArray idArray = @[@"c", @"3", @"4",@"f"];

只是我假设的一个例子。 如何使用 idArray 按 ID 对 A 进行排序?

也就是我想让A变成:

NSArray A= @[[[@"id":@"c"]], [[@"id":@"3"]] ,[[@"id":@"4"]],[[@"id":@"f"]]];

现在,我想请求一个算法来对数组 A 进行排序以获得所需的结果。

---我在google中搜索时得到了我的答案:

NSArray *sorter = @[@"B", @"C", @"E"];
NSMutableArray *sortee = [@[
    @[@"B", @"abc"],
    @[@"E", @"pqr"],
    @[@"C", @"xyz"]
] mutableCopy];

[sortee sortUsingComparator:^(id o1, id o2) {
    NSString *s1 = [o1 objectAtIndex:0];
    NSString *s2 = [o2 objectAtIndex:0];
    NSInteger idx1 = [sorter indexOfObject:s1];
    NSInteger idx2 = [sorter indexOfObject:s2];
    return idx1 - idx2;
}];

如果你想比较两个数组你可以使用

NSArray *array1=@[@"3",@"4",@"c","f"];
NSArray *array2=@[@"c",@"3",@"4","f"];

array1=[array1 sortedArrayUsingSelector:@selector(compare:)];
array2=[array2 sortedArrayUsingSelector:@selector(compare:)];

if ([array1 isEqualToArray:array2]) {
    NSLog(@"both are same");
}
else{
   NSLog(@"both are differnt");
}

或者如果您想从 2 个数组中获取公共元素,请使用

NSMutableSet* set1 = [NSMutableSet setWithArray:array1];
NSMutableSet* set2 = [NSMutableSet setWithArray:array2];
[set1 intersectSet:set2]; //this will give you only the obejcts that are in both sets

NSArray* result = [set1 allObjects];

这将是一个更好的方法来为 A 制作一个字典。然后根据他们的特定值(如智商、姓名等)进行排序

NSArray A = @[[[@"id":@"3"]], [[@"id":@"4"]] ,[[@"id":@"c"]],[[@"id":@"f"]]];
NSArray idArray = @[@"c", @"3", @"4",@"f"];

NSMutableArray *array = [NSMutableArray array];
for (int id = 0;idx<[A count];id++) {
NSDictionary *dict = @{@"Name": A[id],@"IQ":idArray[id]};
[array addObject:dict];
}

NSSortDescriptor *descriptor = [NSSortDescriptor sortDescriptorWithKey:@"IQ" ascending:NO];
[array sortUsingDescriptors:@[descriptor]]