Part of the additions to ES6 is an array method called copyWithin
:
arr.copyWithin(target, start[, end = this.length]) |
The function takes a section of the array and copies it to another place within the array.
target
: index where to copy the elementsstart
: beginning of section to copyend
: end of section to copy. Optional, if not specified the section will go to the end of the array
Example
m
[0,1,2,3,4,5].copyWithin(4, 1, 3) |
Here is a visual representation of what happens:
Remarks
- As expected parameters are 0 based indexes.
- The
copyWithin
modifies the array itself, it does not return a copy of it. - The array size if not modified,
copyWithin
only copies what fits.