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
If you want to insert another array into an array without creating a new one, the easiest way is to use either push
or unshift
with apply
Eg:
a1 = [1,2,3,4,5];
a2 = [21,22];
// Insert a1 at beginning of a2
a2.unshift.apply(a2,a1);
// Insert a1 at end of a2
a2.push.apply(a2,a1);
This works because both push
and unshift
take a variable number of arguments.
A bonus, you can easily choose which end to attach the array from!