A better way to splice an array into an array in javascript

UPDATE: ES6 version

If you're coding in ES6, you can use the "spread operator" (...).

array.splice(index, 0, ...arrayToInsert);

To learn more about the spread operator see the MDN documentation.


The 'old' ES5 way

If you wrap the top answer into a function you get this:

function insertArrayAt(array, index, arrayToInsert) {
    Array.prototype.splice.apply(array, [index, 0].concat(arrayToInsert));
}

You would use it like this:

var arr = ["A", "B", "C"];
insertArrayAt(arr, 1, ["x", "y", "z"]);
alert(JSON.stringify(arr)); // output: A, x, y, z, B, C

You can check it out in this jsFiddle: http://jsfiddle.net/luisperezphd/Wc8aS/


You can use apply to avoid eval:

var args = [start, number].concat(newItemsArray);
Array.prototype.splice.apply(theArray, args);

The apply function is used to call another function, with a given context and arguments, provided as an array, for example:

If we call:

var nums = [1,2,3,4];
Math.min.apply(Math, nums);

The apply function will execute:

Math.min(1,2,3,4);