Javascript - Array copyWithin() Method

The copyWithin() method copies array elements within the array, to and from specified positions.

Description

The copyWithin() method copies array elements within the array, to and from specified positions.

Syntax

array.copyWithin(target, start, end)

Parameter Values

Parameter Require Description
targetRequired.The index position to copy the elements to
start Optional.The index position to start copying elements from (default is 0)
end Optional.The index position to stop copying elements from (default is array.length)

Return

An Array, the changed array

Example

Copy the first two array elements to the last two array elements:

Demo

var myArray = ["XML", "Json", "Database", "Mango"];
console.log( myArray);//from  w  ww  . j a  va 2 s. c o  m
console.log( myArray.copyWithin(2,0));

//Copy the first two array elements to the third and fourth position:

var myArray = ["XML", "Json", "Database", "Mango", "Kiwi", "Papaya"];
console.log( myArray);
console.log( myArray.copyWithin(2,0,2) );

Result

The copyWithin()method copies the array elements within the array to the position starting at target.

The syntax of copyWithin() method:

Array.prototype.copyWithin(target, start = 0, end = this.length) 

The elements that should be copied are taken from the (start, end) range.

The start argument is optional and defaults to 0.

The end argument is optional and defaults to the length of the array.

Example,

let fruits = ["XMLs", "Screens", "Keyboards", "grapes", "guava", "watermelon"]; 
fruits.copyWithin(4); 

console.log(fruits); // ["XMLs", "Screens", "Keyboards", "grapes", "XMLs", "Screens"] 

fruits.copyWithin(4) considers the target index at 4, which is "guava."

It determines the items to be copied will be taken as start at 0 (default) and end at 6 (length of the array).

You can specify start and end values as per your needs:

fruits = ["XMLs", "Screens", "Keyboards", "grapes", "guava", "watermelon"]; 
fruits.copyWithin(4, 1, 3); 
console.log(fruits); // ["XMLs", "Screens", "Keyboards", "grapes", "Screens", "Keyboards"] 

The copyWithin() method accepts negative start indices, negative end indices, and negative target indices.

[1, 2, 3, 4, 5].copyWithin(-3, -4, -1);    // [1, 2, 2, 3, 4] 

When using negative value it counts from the right of the array.

Here, -3 as the target index determines the start position as the third element from the last of the array (which is 3 in the input array).

It determines the start and end values as 2 and 5 (the fourth and first element from the end of the array), respectively.