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
ReverseStack(stack,reversed.push(stack.pop()))
not a function error? 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
You can use something like this:
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()));