Join the social network of Tech Nerds, increase skill rank, get work, manage projects...
 
  • How to delete elements from array while iterating or delete multiple elements from array simultaneously

    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 0
    • 964
    Comment on it

    Sometimes we may face a situation when we need to remove objects from an array while iterating through the same array. We cannot remove elements from the same array on which we are fast enumerating (for in loop). And if we use the traditional "for loop" then the indexes and count of the array change which becomes tricky to handle. So in such condition we can use one of 3 solutions :

    1. Copy objects to another temp array, iterate on temp array and remove elements from main array.
    2. Iterate in reverse order from last to first index.
    3. Use NSIndexSet to remove multiple objects in one go.

    Following example methods show how to remove even numbers from an array :

    // using reverse loop
    -(void)removeElementsFromArrayUsingReverseLoop {
        NSMutableArray *arr = [@[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8"] mutableCopy];
        NSLog(@"original array %@",arr);
        for (int i = arr.count-1; i>=0; i--) {
            int element = [arr[i] intValue];
            if (element%2==0) {
                [arr removeObjectAtIndex:i];
            }
        }
        NSLog(@"array after removing %@",arr);
    }
    
    // using NSIndexSet
    -(void)removeMultipleElementsFromArray {
        NSMutableArray *arr = [@[@"1",@"2",@"3",@"4",@"5",@"6",@"7",@"8"] mutableCopy];
        NSLog(@"original array %@",arr);
        NSMutableIndexSet *indexset = [[NSMutableIndexSet alloc]init];
        for (NSString *str in arr) {
            if ([str intValue]%2 == 0) {
                [indexset addIndex:[arr indexOfObject:str]];
            }
        }
        [arr removeObjectsAtIndexes:indexset];
        NSLog(@"array after removing %@",arr);
    }
    

 0 Comment(s)

Sign In
                           OR                           
                           OR                           
Register

Sign up using

                           OR                           
Forgot Password
Fill out the form below and instructions to reset your password will be emailed to you:
Reset Password
Fill out the form below and reset your password: