Copy an array to the middle of a larger array in Javascript

I looked through the answers here, but I can only find this question for other languages.

So, I have 2 typed Uint8 arrays.

var arr1 = [0,0,0];
var arr2 = [0,1,2,3,4,5,6,7,8,9];

I want to replace the contents of arr2 with arr1, starting from 4th position. So arr2 will be:

arr2 = [0,1,2,0,0,0,6,7,8,9];

If I had not tried to do this in the middle of the array, I could use like this :

arr2.set(arr1);

And I would get:

arr2 = [0,0,0,4,5,6,7,8,9];

I know that I can scroll through arr2 and individually copy the values, but performance is compared to a lot (and performance matters to me because it copies the entire img data array 24 times per second).

Is there any function that can copy to the middle of the array, but with set performance?

+6
3

typedarray.set(array[, offset]) offset.

offset

, . , 0 (.. , 0).

const arr1 = new Uint8Array([0,0,0]);
const arr2 = new Uint8Array([0,1,2,3,4,5,6,7,8,9]);

arr2.set(arr1, 4);

console.log(arr2);
Hide result
+4

slice :

const shim = (source, index, target) => [
  ...source.slice(0, index),
  ...target,
  ...source.slice(index)
]

var arr1 = [0,0,0];
var arr2 = [0,1,2,3,4,5,6,7,8,9];

const newArr = shim(arr2, 3, arr1);
console.log(newArr);
Hide result

.slice ( splice).

+2

All Articles