Had it wrong at first. Should have used concat()
instead.
var a1 = [1,2,3,4,5];
var a2 = [21,22];
var result = a1.slice( 0, 2 ).concat( a2 ).concat( a1.slice( 2 ) );
Example: http://jsfiddle.net/f3cae/1/
This takes a slice()
[docs] of a1
up to the index, then does a concat()
[docs] to add a2
to that array, then uses .concat()
again taking another .slice()
of a1
, but this time starting at the same index through the end.
And add it to Array.prototype
if you wish:
Example: http://jsfiddle.net/f3cae/2/
Array.prototype.injectArray = function( idx, arr ) {
return this.slice( 0, idx ).concat( arr ).concat( this.slice( idx ) );
};
var a1 = [1,2,3,4,5];
var a2 = [21,22];
var result = a1.injectArray( 2, a2 );
You can use the splice()
[docs] method without iterating.
a1.splice( 2, 0, a2 );
http://jsfiddle.net/f3cae/