Say I have two arrays:
var numbers = [1,3,5,7,9,11];
var letters = ['a','b','c'];
And say I have another reference to the numbers array:
var anotherRef = numbers;
I would like to insert one into the other in a way that modifies the existing array, so that after the operation, anotherRef === numbers
.
If I didn't need to maintain the original array, I would do this:
function insert(target, source, position) {
return target.slice(0, position).concat(source, target.slice(position));
}
The problem is, after an insert with this method, the two references point at different arrays:
numbers = insert(numbers, letters, 3);
numbers !== anotherRef; // sadly, true.
If I were adding to the end of the array, I could do this, which is kind of slick:
function insertAtEnd(target, source) {
Array.prototype.push.apply(target, source);
}
Is there a nice way to insert multiple values in place in a JS array?