-1

I have 2 NSArray 's . Like this:

NSArray *array1 = [NSArray arrayWithObjects:@"Frog", @"Cat", @"Dog", Pig];
NSArray *array2 = [NSArray arrayWithObjects:@"Pig", @"Dog", @"Cat",@"Rabbit",@"Hen", nil];

NSMutableArray *intermediate = [NSMutableArray arrayWithArray:array1];
[intermediate removeObjectsInArray:array2];
NSUInteger difference = [intermediate count];

I want to compare array1 with array2...

If array2 has any values or objects of array1 how do I tell what the index paths are for the values that are the same in array2 as the the values in array1.

In other words If Cat and Dog from array1 are found in array2. At which index path is the cat and Dog in array2...

E.g The index paths of Dog and Cat in array2 are 1 and 2 and those 2 values where matched between the 2 arrays.

CapeFurSeal
  • 183
  • 2
  • 13

3 Answers3

1

You should use simple for in loop and NSArray's method

- (NSUInteger)indexOfObject:(id)anObject;

UPDATE:

for(NSString* str1 in array1)
{
    int index = [array2 indexOfObject:str1];
    if (index != NSNotFound)
        NSLog(@"The index is : %d", index);
}

UPDATE2:

For big arrays you can try

NSIndexSet *set = [array1 indexesOfObjectsWithOptions:NSEnumerationConcurrent
                        passingTest:^BOOL(id obj, NSUInteger idx, BOOL *stop) {
                            return [array2 containsObject:obj];
                            }];

to increase performance.

Avt
  • 16,927
  • 4
  • 52
  • 72
0

Simple use Fast Enumeration for that

for(NSString* str1 in array1)
    {
      for(NSString* str2 in array2)
      {
        if([str1 isEqualToString:str2])
           int index = [array2 indexOfObject:str2];
           NSLog(@"The index is : %d", index);
      }
    }
Himanshu Joshi
  • 3,391
  • 1
  • 19
  • 32
0

you can also do this by using blocks, these are pretty good


  NSArray *array1 = [NSArray arrayWithObjects:@"Frog", @"Cat", @"Dog", @"Pig",nil];
  NSArray *array2 = [NSArray arrayWithObjects:@"Pig", @"Dog", @"Cat",@"Rabbit",@"Hen", nil];

 NSMutableArray *indexArray = [[NSMutableArray alloc]init];
 [array2 enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) 
  {  
    if([array1 containsObject:obj])
    {
       [indexArray addObject:[NSNumber numberWithInt:idx]];
    }
}];

NSLog(@"indexes->%@",[indexArray description]);


Shankar BS
  • 8,394
  • 6
  • 41
  • 53