Can you please explain, why in this task forEach() method loops from the end and not from the beginnig of an array, so that I have to reverse() the array to get correct results.
without applying the reverse() your result will look like [4, 3, 2, 1, 5, ] instead [4, 1, 2, 3, 5] which is not what it should be. Moreover, your initial array should remain the same(intact), this is why you apply reverse() second time.
My question was: why without applying reverse() first time: arr1.reverse().forEach(arg=> modif.splice(n, 0, arg)); like arr1.forEach(arg=> modif.splice(n, 0, arg)); => the output is [4, 3, 2, 1, 5, ] instead [4, 1, 2, 3, 5]
How it will work well, if without reversing array the result of arr1.forEach(arg=> modif.splice(n, 0, arg)) => [4, 3, 2, 1, 5, ] and you need [4, 1, 2, 3, 5]
I’m having a hard time understanding your logic or your last response.
I believe the problem is very simple (you can search the forum for how others have solved it if you are really stuck).
You don’t need one reverse or two reverse.
You just need to understand what is being asked of you.
Take one array (arr1) and insert it into the second array (arr2) without changing either arr1 and arr2.
therefore, you need to
1- make a copy of arr2 to be able to do the insertion (use slice)
2- use splice on the copy you made to insert the contents of arr1 into it at the correct spot
3- return the new array
The question is NOT how to solve this problem< it is solved with the code in my first post.
The question is WHY this line of code: arr1.forEach(arg=> modif.splice(n, 0, arg)) gives you the following result : [4, 3, 2, 1, 5, ] when it should be [4, 1,2,3, 5].
Key takeaway here is, what index 1 after each iteration? Remember, n does not change with each passing iteration because you make no adjustments to n during each pass.
YES! That is what I am talking about! It solves the issue. Because you use reverse(). I have hard time understanding why without reversing -first time: arr1.reverse(), forEach()method is looping from end to beginning of the array
ok then! I’m happy for you.
But if it is doesn’t offend you for me to suggest this, i think you should go back and solve this the way it was intended.
The code right now is just not up to the specification given by the exercise (even though it works) and it suggests you have missed the point of this exercise.
(ie. try to solve this one without the forEach)
Good. Hopefully it clears up why you had to do the reverse. The more efficient ways shouldn’t require you to reverse, so you might want to rethink the challenge. If you remember the spread operator from ES6, you would have an even easier time I believe.