JavaScript Array copyWithin() Method Example

The Array.copyWithin() method shallow copies part of an array to another location in the same array and returns it, without modifying its size.

Syntax

array.copyWithin(target, start, end)
  • target(Required) - 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)

Examples

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

var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.copyWithin(2, 0);
output
["Banana", "Orange", "Banana", "Orange"]

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

var fruits = ["Banana", "Orange", "Apple", "Mango", "Kiwi", "Papaya"];
fruits.copyWithin(2, 0, 2);
Output:
["Banana", "Orange", "Banana", "Orange", "Kiwi", "Papaya"]

More Examples

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

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

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

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

[].copyWithin.call({length: 5, 3: 1}, 0, 3);
// {0: 1, 3: 1, length: 5}

// ES2015 Typed Arrays are subclasses of Array
var i32a = new Int32Array([1, 2, 3, 4, 5]);

i32a.copyWithin(0, 2);
// Int32Array [3, 4, 5, 4, 5]

// On platforms that are not yet ES2015 compliant: 
[].copyWithin.call(new Int32Array([1, 2, 3, 4, 5]), 0, 3, 4);
// Int32Array [4, 2, 3, 4, 5]

Comments