Insert an array of values into an array in JavaScript
Yesterday I had an array of objects which needed to be inserted into another array at a specific index point.
// Array #1
["a", "b", "c"]
// Array #2
[1, 2, 3, 4, 5]
// Desired outcome
[1, 2, "a", "b", "c", 3, 4, 5]
But none of the native array methods allowed me to insert an array of values into an array. Splice comes close but it takes a comma delimited list of values, not an array of values. Conveniently however you can still use the native splice function using apply to achieve the desired result.
var arrayOne = ["a", "b", "c"],
arrayTwo = [1, 2, 3, 4, 5],
index = 2;
// We want to push the starting index and the number of values we want
// to delete (in this case 0) onto the beginning of the first array.
arrayOne.unshift(index, 0);
// Next we want to apply the native splice method to arrayOne under
// the context of arrayTwo
Array.prototype.splice.apply(arrayTwo, arrayOne);
// [1, 2, "a", "b", "c", 3, 4, 5]
console.log(arrayTwo);