Push add the element at the end index, it doesn’t work here, unless you like this:
- push the first elements of
arr2
before n
with for loop, or slice it as you did.
- Then in a for loop, push items of
arr1
to result(newArray
).
- At the end, have another loop to push elements left from
arr2
to the result.
is wrong.
I note my tip again. Please considering following example:
var n=1;
var a0=[1,2,3,4];
var a1=[5,6,7];
a0.splice(n,0,a1);
console.log(a0);//logs Array [1, Array [5, 6, 7], 2, 3, 4]
As you see in above sample(the same way you do in your code), splice add while array a1 as one element, rather it’s elements.
Here you go comrade,
More hint:
Have a for loop, to iterate over all elements of a1
array, add access each element of a0
items, and add them using splice to a0
array
var n=1;
var a0=[1,2,3,4];
var a1=[5,6,7];
for(var b=0;b<a1.length;b++){
var item=a1[b];
a0.splice(n,0,item);//it has one small bug! try to figure out
//console.log(a0);
}
console.log(a0);//logs Array [1, 7, 6, 5, 2, 3, 4] , note the order is wrong, find the bug to fix
Feel free to ask for more hint comrade, but try to fix it, it’s so easy, and you are almost done.
Happy programming.