DEV Community

Rajika Imal
Rajika Imal

Posted on

JavaScript quick tips: Array.copyWithin()

Array.prototype.copyWithin() does a copy (shallow) of the selected elements within the same array, to a specified index.

To copy value in index 3 to index 1

const myArray = [1, 2, 3, 4, 5];
myArray.copyWithin(1, 3, 4); // [1, 4, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

To copy all values from specified index to the end to a given index

const myArray = [1, 2, 3, 4, 5];
myArray.copyWithin(1, 3); // [1, 4, 5, 4, 5]
Enter fullscreen mode Exit fullscreen mode

Discussion (0)