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以获得所需的结果。
- - 我在谷歌搜索时得到了答案:
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;
}];
答案 0 :(得分:0)
如果要比较两个阵列,可以使用
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];
答案 1 :(得分:0)
这是为A创建字典的更好方法。然后根据IQ,Name等特定值进行排序。
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]]