-1
NSMutableArray *myIdentityArray = [[NSMutableArray alloc]initWithObjects:@"3",@"1", @"2",@"0", @"0", @"1",@"3",@"1", @"2",@"0", @"0", @"1", nil];

Now How do i create an Array1 with all index that has object 1. for this case it will have 1 , 5, 7 and 11 as its element?

rmaddy
  • 314,917
  • 42
  • 532
  • 579
amystic
  • 5
  • 3

3 Answers3

0

You have to use if condition to check the value of each object, then store the index of the object in the array.

Refer this: Search NSArray for value matching value

Community
  • 1
  • 1
Faiz Mokhtar
  • 938
  • 1
  • 10
  • 24
0

You can use indexOfObject:inRange: method on your NSMutableArray

check this code:

   NSMutableArray *myIdentityArray = [[NSMutableArray alloc]initWithObjects:@"3",@"1", @"2",@"0", @"0", @"1",@"3",@"1", @"2",@"0", @"0", @"1", nil];
    NSMutableArray * array1 = [NSMutableArray array];

    NSUInteger loc = 0;
    NSUInteger len = myIdentityArray.count;

    NSRange range = NSMakeRange(loc, len);
    NSUInteger idx = [myIdentityArray indexOfObject:@"1" inRange:range];

    while (idx != NSNotFound) {
        [array1 addObject:[NSNumber numberWithUnsignedInteger:idx]];
        loc = idx +1;
        len = myIdentityArray.count - loc;
        range = NSMakeRange(loc, len);
        idx = [myIdentityArray indexOfObject:@"1" inRange:range];
    }

    NSLog(@"%@",array1);
0

Do this with a simple loop:

NSMutableArray *myIdentityArray = @[ @"3", @"1", @"2", @"0", @"0", @"1", @"3", @"1", @"2", @"0", @"0", @"1" ];
NSString *search = @"1";

NSMutableArray *results = [NSMutableArray array];

NSInteger index = 0;
for (NSString *str in myIdentityArray) {
    if ([str isEqualToString:search]) {
        [results addObject:@(index)];
    }
    index++;
}

NSLog(@"results = %@", results);
rmaddy
  • 314,917
  • 42
  • 532
  • 579