Search code examples
iosobjective-cnsarray

Find index of all duplicate elements in NSArray


It's hard to explain why I need index of duplicate elements in array. When I tried to fetch the index of element in traditional way it shows only one index, but I need to fetch the all index of duplicate values for ex:

NSArray *array=@[@"one",@"one",@"one",@"two",@"two",@"four",@"four",@"four"];
int index = [array indexOfObject:element];
NSLog(@"index %d",index);

here if I try to fetch index of " one " it shows index is 0 but I need to get further indexes of one


Solution

  • You can fetch the index of duplicates like this:

    NSArray *array=@[@"one",@"one",@"one",@"two",@"two",@"four",@"four",@"four"];
    [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop)
     {
         if ([obj isEqualToString:@"one"])
         {
             NSLog(@"index %d",idx);
    
         }
     }];