JS: Array.prototype.copyWithin

By Xah Lee. Date: . Last updated: .

New in ES2015.

myArray.copyWithin (toIndex, start )

Is same as myArray.copyWithin (toIndex, start , length_of_this ).

myArray.copyWithin (toIndex, start , end )

Move a subarray that began at index start to index end, to the index of toIndex, as many elements as possible without changing the length of the original array.

Returns the changed array.

myArray is modified.

All arguments can be negative. When negative, it's counted from the end.

const ar = [0,1,2,3,4,5];

console.log ( ar.copyWithin ( 2, 0 ) );
// [ 0, 1, 0, 1, 2, 3 ]

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

Reference

ECMAScript® 2016 Language Specification#sec-array.prototype.copywithin

Array Topic

  1. JS: Array Basics
  2. JS: Understand JS Array
  3. JS: Create Array
  4. JS: Sparse Array
  5. JS: Array-Like Object
  6. JS: Array How-To

  1. JS: Array Object
  2. JS: Array.prototype
Liket it? Put $5 at patreon.

Or, Buy JavaScript in Depth

Ask me question on patreon