I'm attempting the following:
var a1 = ['a', 'e', 'f']; // [a, e, f]
var a2 = ['b', 'c', 'd']; // [b, c, d]
a1.splice(1, 0, a2); // expected [a, b, c, d, e, f]
// actual (a, [b, c, d], e, f]
I am confined in my use case by having a2 exist as an array of indeterminant size. Does anyone know of a way to feed splice an array as the substitution, or alternatively a built-in function to do this? I know I could iterate over the elements of a2 and splice them in one at a time, but I'd prefer the fastest method possible because I will need to do this a lot.
Array.splice
supports multiple arguments after the first two. Those arguments will all be added to the array. Knowing this, you can use Function.apply
to pass the array as the arguments list.
var a1 = ['a', 'e', 'f'];
var a2 = ['b', 'c', 'd'];
// You need to append `[1,0]` so that the 1st 2 arguments to splice are sent
Array.prototype.splice.apply(a1, [1,0].concat(a2));