1

I have two arrays:

var arrayA = [ 0, 0, 0 ];
var arrayB = new Uint8Array( 2 );
arrayB[0] = 1;
arrayB[1] = 2;

I would like to copy the values from arrayB to a particular index in arrayA.

For example:

arrayB.copyTo( arrayA, 1 );

arrayA would now become:

[0, 1, 2, 0, 0];

Is there a way of doing this in vanilla javascript without using an iterator?

user1423893
  • 766
  • 4
  • 15
  • 26
  • 1
    There is a [good solution here](http://stackoverflow.com/questions/1348178/a-better-way-to-splice-an-array-into-an-array-in-javascript) – A1rPun Oct 01 '14 at 11:21
  • `Array.prototype.splice.apply( arrayA, [1, 0, arrayB] );` adds the array to the index and not the values of the array. – user1423893 Oct 01 '14 at 11:31
  • Thanks for checking out the link, You need: `Array.prototype.splice.apply(array, [index, 0].concat(arrayToInsert));` – A1rPun Oct 01 '14 at 13:02

1 Answers1

0

This is called "splicing". I'm not sure why you're using the Uint8Array constructor, but if you are working with two normal arrays, this is how I would do it:

var arrayA = [0,0,0];
var arrayB = [1, 2];

var spliceArrays = function(arr1, arr2, index) {
  var arrPart1 = arr1.slice(0, index);
  var arrPart2 = arr1.slice(index);
  return (arrPart1.concat(arr2)).concat(arrPart2);
};

var spliced = spliceArrays(arrayA, arrayB, 1);

console.log(spliced);
Harry Sadler
  • 326
  • 3
  • 7