YAHsaves
YAHsaves

Reputation: 1767

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

I've searched through the answers here, but I can only find this question answered for other languages.

So I have 2 Uint8 typed 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 at the 4th position. So that arr2 will be:

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

If I wasn't trying to do this in the middle of the array I could use set like this:

arr2.set(arr1);

And I would get:

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

I know I can loop through the arr2 and individually copy the values, but performance wise this is very slow compared to set (and performance matters to me because it's copying an entire array of canvas img data 24 times a second).

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

Upvotes: 6

Views: 741

Answers (3)

Eineki
Eineki

Reputation: 14959

Since you are using typed array. Don't you can use the offset of the set method?

arr2.set(arr1, 3)

To overwrite from the 4th element of the target array. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/TypedArray/set

To me it does just what you need, if I understand your question.

Upvotes: 1

Ori Drori
Ori Drori

Reputation: 193130

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

offset Optional

The offset into the target array at which to begin writing values from the source array. If you omit this value, 0 is assumed (that is, the source array will overwrite values in the target array starting at index 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);

Upvotes: 4

Sagiv b.g
Sagiv b.g

Reputation: 31024

You can use the slice method with the spread syntax:

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);

.slice will not mutate the array and will return a new shallow copy of it (unlike splice).

Upvotes: 2

Related Questions