What could be causing my simple recursion function to loop endlessly?

let data = [1, 2, 3]
let sorted = []

let push = function(i) {
  while(i<data.length) {
    sorted.push(data[i])
    push(i + 1)
  }
}

push(0)

Hey there,

I am experimenting with some recursive code and it seems to be stuck in an endless loop. Apologies for the novice question, but I would appreciate if someone could shed some light on this.

Expected outcome: Should simulate a for loop by iterating over an array and pushing elements to a new array. It should stop when reaching i == data.length

Current behavior: It iterates for 0, 1, 2, then back to 2 until hitting a stack overflow.

Codefiddle link: https://jsfiddle.net/t579jbog/

Answer №1

Make sure to use the if statement instead of the while loop, and ensure that you modify the value of i in each recursive call.

let numbers = [1, 2, 3]
let arranged = []

let insert = function(index) {
  if (index < numbers.length) {
    arranged.push(numbers[index]);
    insert(index + 1);
  }
}

insert(0);

console.log(arranged);

Answer №2

Instead of relying on index values, you have the option to use shift() in arrays (shift() function eliminates the first item in the array and returns its value which can then be added into a sorted array).

Afterwards, all you need to do is to verify if the array length is greater than 0; if it is, pass it back to the same function for repeated processing until the array is empty.

To display that values are being retrieved during each iteration, I'm outputting the contents of the sorted array using console.log.

let data = [1, 2, 3]
let sorted = []

let push = function(arr) {
sorted.push(arr.shift())
console.log(sorted);

if(arr.length > 0) {
push(arr); 
}
}


push(data);

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

Tips on retrieving values from input files using jQuery

Is there a way to retrieve the value of an input type using jQuery? Specifically, when I add a file to the input file, I want to dynamically add more input types with the file's value. Currently, I am using the following code: $('#show_input&apo ...

The power of combining React with Three.js

My 3d image is failing to display on the screen. I'm utilizing React with Three.js and encountering the following error message: "THREE.Object3D.add: object not an instance of THREE.Object3D." Below is my component structure: (file tree provided). ...

What steps can I take to stop Node.js from caching 'require' module executions?

After researching, I've come to understand that the require function automatically executes and parses the functions in the module. Is there a way to prevent this automatic execution? Here's the scenario: In order to avoid having an excessively ...

Mistake in closing the component by the parent is causing an issue with Vuetify's v-dialog functionality

Recently, I encountered a situation where a component contained a straightforward v-dialog to display a message to the user and a v-btn to close it. The sequence of events went as follows: The user clicked on the button that triggered the v-dialog's ...

A delivery person is sending a JSON post request with an empty body to the Express server

When I sent a POST request from Postman to the Express server, the body is getting parsed correctly using app.use(express.json()), but it returns an empty body. However, I am able to retrieve params and other information successfully. Strangely, it works ...

What are the steps to view my HTML webpage on a smartphone?

Recently, I successfully created an HTML webpage with CSS and JS that looks and functions perfectly on my PC. However, when attempting to access it on my phone, I encountered some issues. Despite transferring all the necessary files to my phone, only the ...

Passing an array from Javascript to a Spring Controller without relying on jQuery

I am struggling to successfully send an array from my JSP page to a Spring Controller. After populating my array with the necessary data in the JSP, I initiate an AJAX request: var ajaxRequest; try{ // Opera 8.0+, Firefox, Safari aj ...

The middleware for express body-parser stores information in the "name" property

I'm just starting out with the nodeJS Express framework and I'm currently working on consuming a POST request that I sent using the code snippet below: router.post('/', function(req, res) { var data = Object.getOwnPropertyNames(req ...

Implementing AngularJS with varied parameters and functions

Perhaps this issue isn't related to AngularJS, but I'm still new to it and struggling to figure out what's going wrong. Can someone please point me in the right direction? I've been working on this for over 3 hours and it's really ...

Utilizing Event Delegation in jQuery to Handle submit() Events

In my jQuery code, I am using the following: $(this).parents('form').submit(); Initially, it works without reloading the page the first time but subsequent calls result in the page being reloaded. While researching about this issue, I came acros ...

Is it secure to use ES6 in Typescript with nodejs/koa?

As I transition to using TypeScript in a Node.js/koa project, I came across the need to modify the .tsconfig file to target ES6. Otherwise, an error message will appear stating: Generators are only available when targeting ECMAScript 6 or higher. // index ...

Transfer the URL of a template with a PK parameter from JavaScript to Django

I successfully implemented Ajax Search and the results are loaded into a table within a template file. The table header rows are static, and I iterate through each result to append them in < tr > < td >... using a foreach loop. if (data. ...

What is the process for loading a .x model in Three.js?

Could anyone provide guidance on how to successfully load an animated .x model in Three.js? I am currently struggling with the process and have attempted to convert the .x model to collada without success. Unfortunately, my search for a free program to c ...

What is the process of resetting dropdown option values?

Recently, I have encountered an issue with a customized dropdown list in MVC4. I am populating data using AJAX and it is working fine, but the problem arises when the data is not cleared after successfully sending it to the controller. Here's an examp ...

My gadget is caught in a loop, the conditions are failing to function properly

I recently developed a basic web watch application using Tizen Studio specifically designed for Gear watches and similar devices. Within this web watch, I implemented 6 conditions that are intended to change the background of the watch based on the curren ...

Array of dynamically typed objects in Typescript

Hello, I am a newbie to Typescript and I recently encountered an issue that has left me stumped. The problem I am facing involves feeding data to a Dygraph chart which requires data in the format [Date, number, number,...]. However, the API I am using prov ...

Executing the event handler only once

In my React project, I have a button that toggles a boolean state. However, I realized that the button can both set and unset the state due to its toggle functionality. I only want the state to be changed once. Is there a different function I can use ins ...

Utilize GetXmlHttpObject for an AJAX request to interact with a PHP script

I am currently attempting to call a PHP file using the GetXmlHttpObject object and so far, I have had some progress. However, it seems that there is an issue with the URL variable. Do I need to handle the URL string in a different way? Here is the releva ...

Tips for executing a series of getJSON requests sequentially, depending on the outcome of the preceding request

Within my project, I am in the process of collecting data from two distinct sources. Initially, it must iterate through an internal JSON file using loop.each to check if the data is available. If not, it then needs to initiate a second request using $.getj ...

How to find a collision between a spherical object and a triangular shape in a three

In my research, I am exploring the possibility of detecting collisions between a triangle and a sphere in three.js. Currently, I have devised a method using the raycaster and the sphere's vertices. However, this approach has proven to be unreliable a ...