Ren Ren -4 years ago 114
Objective-C Question

Mutable array merge array to another array

I have two mutable arrays:

array1; [containing 1,2,3,4,5]

array2; [containing 9,8,7]

I want to insert array2 values to array1 between 3 and 4, so the result could be:

array1 = [1,2,3,9,8,7,4,5]

Again I want to remove array2 values from array1, so the result could be:

array1 = [1,2,3,4,5]

Please suggest me some best approach to achieve it.

The below links doesn't help:
Copy object at specific index of mutable array to the end of another array

Answer Source

Based on your requirement you can split your first array into 2 part and merge all 3 array to final array for getting expected output.

Please check this code :

    NSMutableArray *mutArray1 = [[NSMutableArray alloc] initWithObjects:@"1",@"2",@"3",@"4",@"5", nil];
    NSMutableArray *mutArray2 = [[NSMutableArray alloc] initWithObjects:@"9",@"8",@"7", nil];

    //You cna change index based on your requirement.
    int indexToSpit = 3;

    //Split your first array into 2 part.
    NSArray *arayFirstPart = [mutArray1 subarrayWithRange:NSMakeRange(0, indexToSpit)];
    NSArray *araySecondPart = [mutArray1 subarrayWithRange:NSMakeRange(indexToSpit, mutArray1.count-indexToSpit)];

    //Merge all 3 array into single array
    NSMutableArray *finalArray = [[NSMutableArray alloc] initWithArray:arayFirstPart];
    [finalArray addObjectsFromArray:mutArray2];
    [finalArray addObjectsFromArray:araySecondPart];

    NSLog(@"Combine Array : %@",finalArray);

    //For remove
    [finalArray removeObjectsInArray:mutArray2];

    NSLog(@"Split Array : %@",finalArray);

Hope this will helps you.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download