JavaScript: Array.prototype.copyWithin

By Xah Lee. Date: . Last updated: .

New in JS2015.

arrayX.copyWithin(at, start)
Take a subarray that began at index start to end, copy them to starting at the index at, override the original values. Return the changed array.
arrayX.copyWithin(at, start , end)
to index end but not include it.
// example of copyWithin

const xx = ["A", "B", "C", "D", "E"];

/*
think of index as between items
["A", "B", "C", "D", "E"]
0   1    2    3    4
*/

// move the slice 3 4, to starting at 0
const xy = xx.copyWithin(0, 3, 4);

console.log(JSON.stringify(xy) === '["D","B","C","D","E"]');
const xx = ["A", "B", "C", "D", "E"];

// move the slice ['A', 'B'] (of index 0 to 2 not including 2), to a position starting at index 1
const xy = xx.copyWithin(1, 0, 2);

console.log(JSON.stringify(xy) === '["A","A","B","D","E"]');

// original is modified
console.log(JSON.stringify(xx) === JSON.stringify(xy));

More examples

console.log([0, 1, 2, 3].copyWithin(0, 0)); // [ 0, 1, 2, 3]
console.log([0, 1, 2, 3].copyWithin(1, 0)); // [ 0, 0, 1, 2]
console.log([0, 1, 2, 3].copyWithin(2, 0)); // [ 0, 1, 0, 1]
console.log([0, 1, 2, 3].copyWithin(3, 0)); // [ 0, 1, 2, 0]
console.log([0, 1, 2, 3].copyWithin(4, 0)); // [ 0, 1, 2, 3]
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 ]
console.log([0, 1, 2, 3, 4].copyWithin(0, 2, 3)); // [ 2, 1, 2, 3, 4 ]
console.log([0, 1, 2, 3, 4].copyWithin(1, 2, 3)); // [ 0, 2, 2, 3, 4 ]
console.log([0, 1, 2, 3, 4].copyWithin(2, 2, 3)); // [ 0, 1, 2, 3, 4 ]
console.log([0, 1, 2, 3, 4].copyWithin(3, 2, 3)); // [ 0, 1, 2, 2, 4 ]
console.log([0, 1, 2, 3, 4].copyWithin(4, 2, 3)); // [ 0, 1, 2, 3, 2 ]

JavaScript: Array, add/remove items

BUY
ΣJS
JavaScript in Depth