Continue looping in Javascript until an empty array is identified

Currently, I am in search of a solution to create a loop in Javascript that continues until the array of objects is empty. The object I am working with looks like this:

"chain": {
    "evolves_to": [{
        "evolves_to": [{
            "evolves_to": [],
            "species": {
                "name": "nidoqueen"
            }
        }],
        "species": {
            "name": "nidorina"
        }
    }],
    "species": {
        "name": "nidoran-f"
    }
}

The goal is to continuously loop until the variable evolves_to is empty and within each iteration, utilize the species.name to display the evolution sequence. For example, "nidoran-f -> nidorina -> nidoqueen". Unfortunately, I have not been able to come up with an effective approach yet. I am feeling slightly lost. Your assistance would be greatly appreciated :)

Answer №1

You have the option to implement a recursive function:

const chain = {
    "evolves_to": [{
        "evolves_to": [{
            "evolves_to": [],
            "species": {
                "name": "nidoqueen"
            }
        }],
        "species": {
            "name": "nidorina"
        }
    }],
    "species": {
        "name": "nidoran-f"
    }
}
, traverse = obj => {
  if(!obj.evolves_to.length) {
    console.log(obj.species.name)
    return
  } else {
    console.log(obj.species.name, "=>")
    traverse(obj.evolves_to[0])    
  }
}

traverse(chain)

Alternatively, you can gather values in an array like below:

const chain = {
    "evolves_to": [{
        "evolves_to": [{
            "evolves_to": [],
            "species": {
                "name": "nidoqueen"
            }
        }],
        "species": {
            "name": "nidorina"
        }
    }],
    "species": {
        "name": "nidoran-f"
    }
}
, arr = []
, traverse = obj => {
  if(!obj.evolves_to.length) {
    arr.push(obj.species.name)
    return
  } else {
    arr.push(obj.species.name)
    traverse(obj.evolves_to[0])    
  }
}

traverse(chain)
console.log(arr.join(" -> "))

Answer №2

One solution is to use a basic recursive function:

const evolutions = { 
  "chain": {
    "evolves_to": [{
        "evolves_to": [{
            "evolves_to": [],
            "species": {
                "name": "nidoqueen"
            }
        }],
        "species": {
            "name": "nidorina"
        }
    }],
    "species": {
        "name": "nidoran-f"
    }
  }
}

function findNoEvolution(obj, evolutionStages) {
  if (obj.evolves_to.length > 0) {
    for (let i = 0; i < obj.evolves_to.length; i += 1) {
      const found = findNoEvolution(obj.evolves_to[i], evolutionStages);
      if (found) {
        evolutionStages.push(obj.species.name)
        return found;
      }
    }
  }
  evolutionStages.push(obj.species.name)
  return true;
}
const evolutionStages = [];
findNoEvolution(evolutions.chain, evolutionStages);
const evolutionStageString = evolutionStages.reverse().join(' -> ');
console.log(evolutionStageString);

After finding the evolution stages, the array is reversed using reverse() and joined together with arrows using join(' -> ').

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 steps can be taken to restrict users to providing only one comment and rating for each item?

In the backend controller, I have the following code snippet: 'use strict'; var Comment = require('../../../models/comment'); module.exports = { description: 'Create a Comment', notes: 'Create a comment&apos ...

Assign a value using the select component from Material UI

I just finished creating a dropdown menu const [selectedValue, setSelectedValue] = useState(''); const handleSelectionChange = (e: any) => { //setSelectedValue(e) console.log('value', selectedValue) } .... <Fo ...

What is the best approach to managing a 204 status in Typescript in conjunction with the Fetch API

Struggling to handle a 204 status response in my post request using fetch and typescript. I've attempted to return a promise with a null value, but it's not working as expected. postRequest = async <T>(url: string, body: any): Promise ...

Issue with jQuery week calendar: Existing data not loading correctly into the calendar

I am currently experimenting with the jQuery week calendar plugin found at https://github.com/themouette/jquery-week-calendar/wiki in order to showcase meetings on my website. However, I am encountering an issue where my events.php file is returning JSON d ...

How can I incorporate a script from the node_modules directory into a VueJS project?

Whenever a node_module is installed, the corresponding folder is automatically added inside the node_module directory of my application. Now, I am looking to include a script that resides within an installed module, such as .. installed_module/dist/ How d ...

Refining strings to enum keys in TypeScript

Is there a method to refine a string to match an enum key in TypeScript without needing to re-cast it? enum SupportedShapes { circle = 'circle', triangle = 'triangle', square = 'square', } declare const square: string; ...

Ways to send a JSON object to a Node.js server

I am working on developing a hybrid mobile application with Node.js as the backend and MongoDB for saving data. My server is functioning properly, and I have set up routes to handle user requests. While I can retrieve data from my server using the GET met ...

AngularJS Uncaught ReferenceError: variable is not

I am facing an issue where I cannot retrieve a value from a function. I am performing REST requests for testing purposes and when trying to get a date, it always returns undefined. An Illustration $http.get('app/components/home/controller/test_calen ...

What is the best way to retrieve data from a JSON object?

Can the status variable be used as a JSON object? What is the method to access the values of action_success and newIndex within the status object? Server: [HttpPost] public ActionResult UploadFiles() { // save file.. return Json(new { action_suc ...

Using jQuery Plugin for Date Operations

I am in search of a jQuery tool that can assist me with date manipulations, such as: 1) Adding a specific number of days to a date and obtaining a new Date. 2) Determining the week of the year for a given date. 3) Calculating the number of days between two ...

programming for the final radio button text entry

I am struggling with a form that has 5 radio buttons, including an "other" option where users can manually enter text. The issue I'm facing is that the form only returns the manual entry text and not any of the preset radio values. I need it to work f ...

Can we convert oddly structured data to XML format?

I have some sample output data that resembles JSON but is not formatted exactly like it. I am curious about converting this data into XML format using PHP. Can someone help me with this? [{ action: 'getallregions', reply: [{ regionid: &a ...

Using Node and Express to handle form submissions, we can create a POST request that sends data to the server

Despite my ongoing learning journey, I am feeling a bit frustrated as I struggle to find a solution for this particular issue using ES6 Javascript. Currently, I have a straightforward todo-list web-app where everything is managed and displayed through the ...

Display/Conceal content with JQuery on a PHP webpage

I am having trouble with the following code. My intention is to show/hide the content between the #info id when clicking buttons, but nothing seems to be happening. Could you help me identify the issue? echo '<script> $( "#show' . $r ...

"Sending a POST request from the smartphone application client developed using the Meteor

I'm currently working on a simple mobile app with Meteor that aims to send user location data to a geospatial database or server. However, I'm facing some challenges and uncertainties about the feasibility of this task using Meteor. The issue ari ...

assigning a numerical value to a variable

Is there a way to create a function for a text box that only allows users to input numbers? I want an alert message to pop up if someone enters anything other than a number. The alert should say "must add a number" or something similar. And the catch is, w ...

Issue encountered when trying to load a Jquery Datatable with input from a textbox

Seeking assistance with this issue. This is the code for my Controller: namespace PruebaBusquedaRun.Controllers { public class TestController : Controller { MandatosModel md = new MandatosModel(); // GET: Test public ActionResult Index() ...

Cross-origin request headers not permitted by the Access-Control-Allow-Headers policy in NodeJS and ExpressJS

I am currently facing an issue with my NodeJS + ExpressJS client-server setup while making API requests to a backend server. Every time I make an API request, I receive the following error: Request header field firstname is not allowed by Access-Control-A ...

Retrieving a specific variable from a cookie value that is stored within a JSON array

Is there a way to pass a single variable from a JSON array stored in the qookie file value to JavaScript? The qookie code looks like this: <?php $cookie_key = 'count'; CookieManager::store($cookie_key, json_encode(array( 'SameSite&ap ...

The Ocelot API Gateway is a powerful tool for managing

I encountered an issue while working on my API gateway project. I initially installed the latest version of Ocelot (16.0.1), but it did not function correctly. The problem was resolved by reverting back to Ocelot version 15.0.6, while keeping my .NET Core ...