Introduction :
Javascript copyWithin() method is used to copy a portion of one array in the same array in a range. copyWithin doesn’t modify the array size. It just copies the elements to separate indices. This method is useful if you want to copy one part of the array or subarray to another part.
In this tutorial, I will show you how to use copyWithin method to copy array elements to another position in the same array.
Syntax of copyWithin :
The syntax of copyWithin method is as below :
arr.copyWithin(target: number, start: number, end: number)
Here,
-
target: The index position to start the copy operation.
-
start: Start index to pick the subarray for copy.
-
end: End index to pick the subarray for copy. If not provides, length of the array is taken by default.
We can also pass negative values for these parameters.
-
negative target: it is treated as array length + target
-
negative start: it is treated as array length + start
-
negative end: it is treated as array length + end
Examples :
1. With target, start, and end :
var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
myArray.copyWithin(4, 0, 5);
console.log(myArray);
Output :
[ 1, 2, 3, 4, 1, 2, 3, 4, 5 ]
It will replace all elements starting from index 4 and it will replace elements from index 0 to index 5 (i.e. up to index 4).
2. With target and start :
If we don’t pass the end value :
var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11];
myArray.copyWithin(4, 0);
console.log(myArray);
Output :
[ 1, 2, 3, 4, 1, 2, 3, 4, 5, 6, 7 ]
It replaces all items starting from index 4 and replaces all items from index 0 to the end.
3. Negative target, start, and end :
Let’s try with negative values :
var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
myArray.copyWithin(-8, -10, -8);
console.log(myArray);
The size of the array is 10. So,
target : 10 - 8 = 2 start : 10 - 10 = 0 end : 10 - 8 = 2
Output :
[ 1, 2, 1, 2, 5, 6, 7, 8, 9, 10 ]
4. What about start > end :
If the value of start is greater than the end :
var myArray = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
myArray.copyWithin(4, 10, 4);
console.log(myArray);
It will print :
[ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
No change to the array.