سؤال

Its really a simple question but I want a short way to compare two array to get index of containing object. For example we have two arrays....

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

After comparison from array2 to array1, I want the index of the containing object in array1.

I tried to check the this link but I didn't get ans as I expected Fastest way to check if an array contains the same objects of another array

هل كانت مفيدة؟

المحلول

For getting indexes of objects in array1 which are also present in array2, you can use:

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
}];

نصائح أخرى

Use following method to get compare index from array 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);
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");
        }
    }
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top