Search code examples
javascriptarraysstackreverse

how can I reverse my array using only one Array instead of using two?


I am fairly new to JavaScript and programming in general. I was experimenting with some code to reverse an array with push and Pop. I know I can use Array.prototype.reverse() but I wanted to experiment and play around.

here are my questions

  • 1) why do I get undefined in the last line of code? since I returned the array?
  • 2) why ReverseStack(stack,reversed.push(stack.pop())) not a function error?
  • 3) how can I get the same result but without using a second array? using only push & pop

const stack = [];
const reversed = [];
stack.push("a");
stack.push("b");
stack.push("c");
stack.push("d");
stack.push("e");
stack.push("f");

ReverseStack = (stack, reversed) =>{

    for(let i = 0; i <= stack.length; i++) {
        if (stack.length === 0){
            console.log(reversed); //output [ 'f', 'e', 'd', 'c', 'b', 'a' ]
            return reversed
        }
        else{
            reversed.push(stack.pop()); //store popped item in poppedItems
            ReverseStack(stack,reversed)

            //why the below does not work? it says reversed.push is not a function
            //ReverseStack(stack,reversed.push(stack.pop()))
        }
    }
};

console.log(ReverseStack(stack, reversed)); //output undefined ? why is that


Solution

  • You can use something like this:

    Idea:

    • Remove first item and save it.
    • Repeat the process for remaining items till length is 1.
    • Push stored values in returned array.

    Note:

    • Array.pop is different from Stack.pop. Array.pop removes last element and Stack.pop removes first. You can use Array.shift for this.

    Following is a sample:

    const stack = [];
    stack.push("a");
    stack.push("b");
    stack.push("c");
    stack.push("d");
    stack.push("e");
    stack.push("f");
    
    ReverseStack = (stack) => {
      if (stack.length > 1) {
        const head = stack.shift();
        const reverse = ReverseStack(stack);
        reverse.push(head)
        return reverse;
      }
      return stack;
    };
    
    console.log(ReverseStack(stack.slice()));