Is there a way to invert my array by utilizing just a single array instead of resorting to using two arrays

While I am still learning JavaScript and programming as a whole, I decided to test out some code for reversing an array using push and pop methods. Even though I am aware that I could easily utilize Array.prototype.reverse(), I wanted to have some fun experimenting.

These are the questions that came up during my experimentation:

  • 1) Why do I encounter 'undefined' in the last line of code even though I returned the array?
  • 2) Why does
    ReverseStack(stack,reversed.push(stack.pop()))
    not work and throw a 'not a function' error?
  • 3) Is there a way to achieve the same result without relying on a second array but only using push and 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());
            ReverseStack(stack,reversed);
            // This part doesn't work: it says reversed.push is not a function
            // ReverseStack(stack,reversed.push(stack.pop()))
        }
    }
};

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

Answer №1

Here's a simple method you can follow:

Procedure:

  • Remove the first item and keep it aside.
  • Continue this process for the remaining items until only one item is left.
  • Add the stored values to the returned array in reverse order.

Please take note of the following:

  • Array.pop operates differently from Stack.pop. While Array.pop removes the last element, Stack.pop removes the first one. To achieve similar functionality as Stack.pop, you can use Array.shift.

Below is an example to illustrate the process:

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()));

Answer №2

1) I'm confused as to why I am getting undefined in the final line of code even though I have returned the array?

The function you've created is recursive. While you do return the reversed on the final condition, there is no return statement when the else block is executed. To ensure the return value propagates back to the outer caller of ReverseStack, you need to add a return statement for the recursive call within the else block:

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());
            return ReverseStack(stack,reversed)

            //the below approach doesn't work because reversed.push is not a function
            //ReverseStack(stack,reversed.push(stack.pop()))
        }
    }
};

console.log(ReverseStack(stack, reversed)); //why does this output undefined?

2) Why am I encountering a "not a function" error with ReverseStack(stack,reversed.push(stack.pop()))?

This error occurs because the .push method returns the new length of the array, not the mutated array itself. Therefore, the recursive call of

ReverseStack(stack,reversed.push(stack.pop()))

is passing two arguments to the function: an array and an integer instead of an array like it expects.

3) Is there a way to achieve the same result without using a second array and only utilizing push & pop?

Achieving the desired outcome without introducing another array or data structure while solely relying on push and pop operations might be challenging, perhaps even impossible. An alternative method using indices involves iterating from the middle of the array and swapping elements sequentially without recursion:

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

ReverseStack = (stack) => {
  for (let i = Math.ceil((stack.length - 1) / 2); i < stack.length; i++) {
    [stack[i], stack[stack.length - i - 1]] = [stack[stack.length - i - 1], stack[i]]
  }
  return stack;
};

console.log(ReverseStack(stack));

Answer №3

The reason for the function ReverseStack returning an implicit undefined value is that the return statement is located within the if block rather than outside of the if-else block.

It seems unnecessary to log or return the result of the function ReverseStack since you are making modifications directly to the array reversed in memory.

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

let ReverseStack = (stack, reversed) => {
  for (let i = 0; i <= stack.length; i++) {
    if (stack.length !== 0) {
      reversed.push(stack.pop());
      ReverseStack(stack, reversed);
    }
  }
};

ReverseStack(stack, reversed);
console.log(reversed);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the method to convert Javascript values from pixels to percentages?

Is it possible to change the scrolltop value dynamically based on a percentage of the user's screen size? I've been trying to achieve this using JS but haven't had any luck. Here is a link to a codepen that showcases the issue: [link] (http ...

Why am I experiencing a problem with my ajax call only working once when I submit forms that are rendered with @Html.Render

I have a scenario where my index page loads with two partial views, each containing an ajax call that filters content based on date. The issue I'm facing is that the ajax call only works once successfully, and subsequent attempts cause a full page ref ...

Defining variables within a jQuery function

Within my initialization function (init), I have defined some variables and an animation that utilizes those variables. The challenge arises when I want to use the same animation/variables in my clickSlide function. http://jsfiddle.net/lollero/4WfZa/ (Un ...

Establishing the default value of an input field in Angular by referencing another field

Within an Angular (1.5) setting, I am confronted with a form containing two input sections: ID URL The requirements are as follows: If the ID section remains vacant, the URL field should likewise be left empty. If the URL area is entered manually, it ...

Are Opera and IE9 blocking cross-origin Ajax requests?

I have been utilizing the following page - - to initiate a cross-origin Ajax request towards this specific resource: The functionality appears to be functioning as expected in Chrome, Safari, and Firefox, but encounters an issue in IE9 and Opera. Below ...

What is the most effective approach for managing exceptions at a global level in Node.js using Express 4?

Is there an Exception filter available in node.js with express 4, similar to the one in asp.net MVC? I have searched through various articles but haven't found a solution that meets my requirements. I also attempted the following in app.js: process ...

utilize forEach method in JavaScript to showcase images

I am having trouble displaying images in the "images" folder on my view. The path seems to be correct and there are no errors displayed in the browser console. Can someone please help me troubleshoot this? function Abstract() { let images = [...docu ...

Using AngularJS directives in Markdown

I am currently working on creating a custom HTML directive using AngularJS that will allow me to display Markdown content in the browser. My goal is to have a <markdown> element with a src attribute that will dynamically load and render the specified ...

Mastering the Javascript ++ and += Operators

I'm struggling with a simple movement engine I created. When the Up key is pressed, a function moves a small div up, and when the Down key is pressed, it does the opposite. I suspect the issue lies with the += in the Down() function, as changing it to ...

Implementing Checkbox Functionality within a Dropdown Menu using AngularJS or JavaScript

I am interested in finding a multi-select checkbox solution similar to the one demonstrated here: Instead of using jQuery, I would prefer options in AngularJS or pure JavaScript. Does such a solution already exist in these frameworks, or is there guidance ...

Toggling the visibility of a div using JavaScript

When I click the button, I want to show and then hide a div. However, it doesn't work on the first click - only on the second click. How can I make it work on the first click? HTML <p>Click the button</p> <button onclick="myFu ...

Interference + brochure + plotly - temporary clicks

I have come across a reproducible example that I found at the following link: https://bl.ocks.org/timelyportfolio/5ab450e90ee510f4df9758b9ec5a8ad0. library(sf) library(plotly) library(leaflet) library(crosstalk) library(htmltools) boroughs_data <- st_ ...

When a single object is modified in a JavaScript array, all the elements are affected

I am working with an array of 71 objects: var data = [] This array is populated with data from a database, containing both static and dynamic elements for each object in the data. angular.forEach(returnData,function(value,index) { if(!Array.isArray(va ...

JavaScript code for extracting the value of a specific table cell from the provided screenshot

Looking at the image below, as someone new to JavaScript development, I have two questions. First, how can I directly retrieve the value of the second td from $('#cart-subtotal-order.total.subtotal td') in JavaScript code? Secondly, I need to kno ...

The character is having trouble displaying correctly in the ajax response

I've been searching for solutions but nothing seems to help. The issue I'm facing is with reading characters from an AJAX response. How can I properly read characters that are coming from an AJAX response in the form of a JSON object? ["label" ...

How come the font size and div elements combine when I drag and drop the items?

Recently, I decided to create my own drag and drop game. The game is almost complete, but there's one issue. When I try to drop the items into the designated "Drop Items Here" area, their style changes abruptly to mimic the text. For example: https: ...

Counting occurrences of characters in a string: A simple guide

I'm working on a function to identify characters from an array within a given string and count how many of them are present. I've attempted to cover every possible pattern, but the task seems overwhelming. I also experimented with the alternativ ...

html carousel not updating in popover

I've been attempting to create a popover with a bootstrap carousel, where the carousel items are dynamically generated and appended from a script. Despite my efforts, I have successfully displayed the carousel but struggle to append the items. I' ...

Converting an array of objects into a dictionary using TypeScript

I'm attempting to convert an array of objects into a dictionary using TypeScript. Below is the code I have written: let data = [ {id: 1, country: 'Germany', population: 83623528}, {id: 2, country: 'Austria', population: 897555 ...

What is the best way to generate a JSON output that contains the entire

The use of {foo|json} is effective for displaying only part of the $scope. Is there a way to pass the entire scope to the json filter? ...