Search code examples
javascriptarraysmethods

Reversing array, pop method in loop not popping to completion


note: I have been looking at code for hours now and am at the point where I am beginning to question the spelling of every word or wonder if I am dyslexic- I know this is an easy question

I am looking to write a basic function (without the use of standard JavaScript reverse method) that given an array, creates a new array with the same values in reverse order.

Why does this function as written pop "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"]));

This should log ["C", "B", "A"] however it is logging → ["C", "B"] and when I log arr within the function it holds onto "A".

I fixed this by adding reversedArr.push(arr.pop(arr[0])); after the for loop and before the return statement which fixes the problem, but if the for loop is written to continue while i is less than the array length and when the array only contains "A", the length is one, and i is 0, shouldn't it also pop "A"?

What am I missing here?


Solution

  • When you do a pop on array it will permanently take that item out of the array and changes it's length. See here

    So, in your code you should use

    var popped = arr[i];
    

    And do the reverse iteration as below:

    for (var i = arr.length -1; i>=0 ; i--)