Note: I've been immersed in code for hours now and have reached a stage where I'm starting to doubt the spelling of every word or question if I have dyslexia. Despite this, I know this should be a simple question.
I want to create a basic function (without relying on the standard JavaScript reverse
method) that, when given an array, generates a new array with the same values but in reverse order.
Why does the current function remove "C" and "B", but not "A"?
function reverseArray(arr) {
var reversedArr = [];
for (var i = 0; i < arr.length; i++) {
var popped = arr.pop(i);
reversedArr.push(popped);
}
return reversedArr;
}
console.log(reverseArray(["A", "B", "C"]));
Even though the expected outcome is ["C", "B", "A"], it's actually showing only → ["C", "B"]. When I check the array within the function, "A" is still present.
To solve this, I've included
reversedArr.push(arr.pop(arr[0]));
after the for loop and before the return statement. This resolves the issue, but considering that the for loop should continue while i is less than the array length and when the array only contains "A", where the length is 1 and i is 0, shouldn't it also remove "A"?
What am I overlooking here?