TypeScript Array.prototype.copyWithin() Method
Last Updated :
12 Feb, 2024
The copyWithin() method is available in the TypeScript Array.prototype it helps you to rearrange the elements within the array by copying a sequence of array elements. This method is good for tasks such as shifting elements, removing them without creating gaps, or copying portions of arrays.
Syntax
array.copyWithin(target, start, end)
Parameters:
- target: It contains the index position from which the copying of elements will start.
- start (optional): It contains the index position of the first element to copy (defaults to 0).
- end (optional): It contains the index position of the last element to copy (excluding it) (defaults to the array’s length).
Return Value:
This method returns the same array instance (not a new array), allowing for chaining.
Example 1: The below example is the basic implementation of copyWithin() method with two parameters.
Javascript
const geeks: string[] =
[ 'GFG' , 'JavaScript' , 'GFG' , 'TypeScript' ];
geeks.copyWithin(1, 3);
console.log(geeks);
|
Output:
["GFG", "TypeScript", "GFG", "TypeScript"]
Example 2: The below code implements the copyWithin() method with three parameters.
Javascript
const geeks: string[] =
[ 'JavaScript' , 'TypeScript' , 'GeeksforGeeks' , 'GFG' ];
geeks.copyWithin(2, 1, 3);
console.log(geeks);
|
Output:
["JavaScript", "TypeScript", "TypeScript", "GeeksforGeeks"]
Share your thoughts in the comments
Please Login to comment...