比较两个数组以获取包含对象的索引

时间:2014-05-14 11:48:20

标签: arrays ios7 nsarray nspredicate

这真的是一个简单的问题,但我想要一个简短的方法来比较两个数组来获取包含对象的索引。例如,我们有两个数组......

NSArray *array1=@[@"b",@"a",@"c"];
NSArray *array2=@[@"c",@"b",@"a"];

在从array2到array1的比较之后,我想要array1中包含对象的索引。

我试图检查这个链接,但我没有像我预期的那样得到ans Fastest way to check if an array contains the same objects of another array

3 个答案:

答案 0 :(得分:1)

要获取array1中同时存在于array2中的对象的索引,您可以使用:

NSIndexSet* indexes = [array1 indexesOfObjectsPassingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
    return [array2 containsObject:obj];
}];
[indexes enumerateIndexesUsingBlock:^(NSUInteger idx, BOOL *stop) {
    NSLog(@"Index is %u", idx);  //do whatever you need to do with the index
}];

答案 1 :(得分:0)

使用以下方法从数组1获取比较索引:

    NSMutableArray *arrayFirst = [[NSMutableArray alloc] initWithObjects:@"b",@"a",@"c", nil];
    NSMutableArray *arraySecond = [[NSMutableArray alloc] initWithObjects:@"c",@"b",@"a", nil];
    NSMutableArray *arrayComparedIndex = [[NSMutableArray alloc] init];

    for(int i =0; i<[arrayFirst count]; i++)
    {
         if ([arraySecond containsObject:[arrayFirst objectAtIndex:i]])
         {
                NSLog(@"index - %d",i);
                [arrayComparedIndex addObject:[NSString stringWithFormat:@"%d",i]];
        }
    }
    NSLog(@"arraythree - %@",arrayComparedIndex);

答案 2 :(得分:-2)

for (int i = 0; i < array1.count; i++) {
        NSString *s = array1[i];
        NSInteger anIndex = [array2 indexOfObject:s];

        NSLog(@"Index of %@ is: %d", s, anIndex);

        if (NSNotFound == anIndex) {
            NSLog(@"not found");
        }
    }