Reputation: 1810
I have two mutable arrays:
NSMutableArray
array1; [containing 1,2,3,4,5]
NSMutableArray
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
Upvotes: 0
Views: 836
Reputation: 8351
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.
Upvotes: 3
Reputation: 1178
var array1 = [1,2,3,4,5]
var array2 = [9,8,7]
for inserting array2 at index 3 use
array1.insertContentsOf(array2, at: 3)
print(array1)
for removing you can either use
array1 = Array(Set(array1).subtract(array2))
which will be unordered array as we are converting a Array to Set for subtraction.
or you can try
var array3 = [1,2,3,4,5]
//assuming array1 as [1,2,3,9,8,7,4,5]
let array4 = array1.filter({array3.contains($0)})
print(array4) //will give you desired ordered array
Upvotes: 0