I have a place in my javascript code where I need to do an operation like
copying a specified range from one array into specified range in another array.
The operation is similar to
1) System.arraycopy in java ->
System.arraycopy(array1, index1, array2, index3, index4 - index4 + 1);
2) copy in go ->
copy(array2[index3:index4 + 1], array1[index1:index2+1])
3) slice in python ->
array2[index3: index4 + 1] = arr[index1: index2+1]
For now I am iterating it by hand and doing it. But I did not any util function in js to do that. Is there really one ?
Update 1: It should exactly only copy and not add or remove elements from any of the two given arrays.
It should behave like this implementation:
function arraycopy(src, srcPos, dst, dstPos, length) {
let j = dstPos;
let tempArr = src.slice(srcPos, srcPos + length);
for (let e in tempArr) {
dst[j] = tempArr[e];
j++;
}
};
Update 2: (See some answers below with caution and see if it will fit your use case(like in huge dataset case)) Many answers below used splice in such a way it will break, if the range start to end in source array is huge. It will throw "RangeError: Maximum call stack size exceeded"... as it will exceed the maximum allowed number of arguments in a function. (try demo script here) "