What is the more efficient way to insert an array inside another array.
a1 = [1,2,3,4,5];
a2 = [21,22];
newArray - a1.insertAt(2,a2) -> [1,2, 21,22, 3,4
Had it wrong at first. Should have used concat() instead.
var a1 = [1,2,3,4,5],
a2 = [21,22],
startIndex = 0,
insertionIndex = 2,
result;
result = a1.slice(startIndex, insertionIndex).concat(a2).concat(a1.slice(insertionIndex));
Example: http://jsfiddle.net/f3cae/1/
This expression uses slice(0, 2)[docs] to return the first two elements of a1 (where 0 is the starting index, and 2 is the element deleteCount, though a1 is not altered).
Intermediate result: [1,2]
It then uses concat(a2)[docs] to append a2 to the end of the [1,2].
Intermediate result:[1,2,21,22].
Next, a1.slice(2) is called within a trailing .concat() at the tail end of this expression, which amounts to [1,2,21,22].concat(a1.slice(2)).
A call to slice(2), having a positive integer argument, will return all elements after the 2nd element, counting by natural numbers (as in, there are five elements, so [3,4,5] will be returned from a1). Another way to say this is that the singular integer index argument tells a1.slice() at which position in the array to start returning elements from (index 2 is the third element).
Intermediate result: [1,2,21,22].concat([3,4,5])
Finally, the second .concat() adds [3,4,5] to the the end of [1,2,21,22].
Result: [1,2,21,22,3,4,5]
It may be tempting to alter Array.prototype, but one can simply extend the Array object using prototypal inheritance and inject said new object into your projects.
However, for those living on the edge ...
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 );