type or paste code here
let newArr = [];
newArr = arr2.slice(0);
newArr = newArr.splice(n,0,...arr1);
//newArr = newArr.splice(n,0,4); //when I do this for test ..it still not working . what is the problem with my splice() ?
return newArr;
what is going on with my splice() ? I can not understand . please help me out.
The letter n isnot defined in your code. Either define a variable n and assign an index number to it or replace then with the correct index number inside the splice call.
but n is an argument in function . then why I should define it again ? please
its like -
type or paste code here
function func(arr1,arr2,n){
let newArr = [];
newArr = arr2.slice(0);
newArr = newArr.splice(n,0,...arr1);
//newArr = newArr.splice(n,0,4); //when I do this for test ..it still not working . what is the problem with my splice() ?
return newArr;
}
Sorry, in the previous code snippet you didn’t paste the function definition so i couldn’t guess that. At this point, if you have pasted all your code please also paste a link to the challenge you are working on so i can compare your code to the requirements.
Also note that the second parameter in splice refers to how many items you want to delete or replace. So putting zero there means nothing is removed or replaced. Just the new value is added.
Ok thx. So your current code looks good to me. But you said you are trying the last line? Why do you think the last line should work? It just adds 4 to newArr which is not what the test wants…
I was checking the splice is working or not … At that time I cut the before line . but 4 was not added to the arry . I think you ran the code . then you will understand what I am saying about.
Return the newArr without assigning it to the return value from splice.
Above is the splice documentation.
It says that if splice doesn’t delete anything the returned array is blank.
So just write:
newArr.splice(n,0,…arr1);
And return newArr without assigning the return value as it will be blank.
you are not supposed to change the any of the arrays. if you use splice on arr2, you would not pass the test beacause unlike slice(), splice() alters the main array. you would have to clone arr2 in a way it will not be affected after it has been clone to a new variable(use the spread operator for that). also you are meant to copy arr1 into arr2 so why are you slicing arr2?. you are to slice arr1 into arr2
i responded by message so as not to spoil the solution.
The issues in the code were:
wrong function name (the original name was changed)
the splice returns an empty array when nothing is being removed and the OP was returning this empty array which is not correct. the OP needed to return the newArr instead.