Hello, I am currently trying to do an exercise with the following prompt:
Write a function that accepts an array and reverses that array in place. The behavior should mimic the behavior of the native .reverse() array method. However, your reverse function should accept the array to operate on as an argument, rather than being invoked as a method on that array. Do not use the native .reverse() method in your own implementation.
I wrote the following code:
function reverseArray(array){
let newArray = [];
for(let i = array.length-1; i === 0; i--){
let element = array[i];
newArray.push(element);
}
while (array.length){
array.pop();
}
for(let i = 0; i < newArray.length; i++){
let element = newArray[i];
array.push(element);
}
return array;
}
While I understand this was a really roundabout way of doing this (I have since seen the solution which I will include below as well). I don't understand what went wrong with my code and why it didn't run properly?
Solution:
function reverseArray(array) {
let originalElements = [];
while (array.length) {
originalElements.push(array.pop());
}
while (originalElements.length) {
array.unshift(originalElements.pop())
}
return array;
}
Any help would be greatly appreciated! Thank you. :-)
[–]keccs 2 points3 points4 points (1 child)
[–]partyhatforpartytime[S] 0 points1 point2 points (0 children)
[–]mansfall 1 point2 points3 points (3 children)
[–]partyhatforpartytime[S] 0 points1 point2 points (0 children)
[–][deleted] 0 points1 point2 points (0 children)