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

Leverage AngularJS to effectively parse JSON data using scope variables

I am trying to JSON parsing in AngularJS using $stateParams in the controller below: rerunApp.controller('rerunCategoryListCtrl', function($scope, $http, $stateParams) { var stpNameCat = $stateParams.nameCat; $http.get(JSON UR ...

Implementing TypeScript for augmented styling properties in a component - a guide

I have custom components defined as follows: import React from 'react'; import styled from '../../styled-components'; const StyledInput = styled.input` display: block; padding: 5px 10px; width: 50%; border: none; b ...

Having difficulties showing live data in real-time, the Python web application is encountering an "Internal Server Error" while attempting to do so

The application is receiving real-time data (verified by using an alert), but when trying to display it on the card, an Internal Server Error occurs. The same code runs fine as an independent HTML page but not in a Flask Python web app. <!DOCTYPE ...

What is the best way to showcase the chosen items from a treeview in ReactJS?

I'm struggling to figure out how to showcase the selected elements from my treeview. Any ideas or tips? The main purpose of this treeview is to filter data for export purposes. You can find the original code here. import React, {useEffect, useState} ...

Node.js program experiences issues with incorporating netCDF files

I am attempting to encode a NetCDF file within my Node.js program using the netcdf library, which can be found at https://www.npmjs.com/package/netcdf. After running the program, I encountered the following error: C:\app [master +2 ~1 -0 !]> npm ...

"Learn how to create a scrolling div using a combination of CSS and JavaScript with absolute and relative

After relying solely on "pre-made" components like Mui or TailWind, I decided to create a component using only CSS and maybe JavaScript. However, I encountered some difficulties when attempting to position a div inside an image using relative and absolute ...

Connect the child content to the form

Are there any methods to connect a projected template (ContentChild) to the form specified on the child, such as adding formControlName after it has been rendered? I am having difficulty in finding relevant information online, possibly due to using incorr ...

Iterating Through Array with Node JS Before Adding a New Property

There is a JSON input with data connected to a secondary model called Users. To process this, I need to iterate through listingData.Agents to extract the index ID and then use this ID to find the corresponding user. The challenge here is that due to asynch ...

Updating a MongoDB subarray with $set now includes adding a new entry rather than just updating existing ones

When trying to update an object in a sub-array, instead of replacing and updating the data, it adds a new entry. Here is the code from controller.js: const updateSubCategory = asyncHandler(async (req, res) => { const { dataArray } = req.body ...

Is there a method to determine the height of the viewport if the DOCTYPE is not specified in Chrome, Firefox, or Safari?

How can we accurately determine the viewport's height even if the DOCTYPE is not specified? When the DOCTYPE is missing, values that would typically be around 410 may instead show as 3016. Is there a solution for finding the viewport's height wi ...

Sending a JSON payload along with a file using Delphi

I am a beginner in Delphi and I am looking to send a JSON string along with additional files using a single HTTP POST method. However, when I use the TIdHTTP class, the sent JSON text breaks and becomes unusable. Can anyone provide guidance on how to sol ...

Exploring the capabilities of AngularJS for efficient testing using Jasmine alongside mixpanel integration

Within my AngularJS application, I implement MixPanel for analytics by using the asynchronous script in my index.html file. index.html <script type="text/javascript">(function(e,b){if(!b.__SV){var a,f,i,g;window.mixpanel=b;a=e.createElement("script ...

Iterating through a jQuery function to increment value

I have encountered an issue while trying to calculate the total value from an array of form fields. The problem lies in how the final value is being calculated on Keyup; it seems that only the last inputted value is being added instead of considering all t ...

Error: Sorry, there was an issue with the code (React)

I'm attempting to build a React project without Node, and I'm trying to call a JS file from an HTML file. This is just a simple example for learning purposes. However, I keep encountering the Uncaught SyntaxError: Unexpected token '<&apos ...

In Vuex, the getters always come back as true

The isLoggedIn in getters is always true even if there is no token from API. I can still go to every route; I don't know what the error is in the guard route or if I'm storing the token wrong in the state. This statement is not working: if(!store ...

The Iron Seal feature is ineffective when a user tries to log in

Iron.seal isn't properly updating the npm module Iron, which is causing login issues for users. var obj = { a: 1, b: 2, c: [3, 4, 5], d: { e: 'f' } }; var password = 'some_not_random_password_that_is_at_lea ...

Is it possible to make the info box centered and adjust everything to seamlessly fit on all screen sizes?

Is there a way to create a centered info box that stretches to fit any screen size? ...

best practice for parsing JSON strings in Java

I have a JSON string/response that I need to parse in a simple way to extract objects/arrays. The structure may be complex and repeated, so I need to retrieve the data list by list. Most parsers only work with basic JSON structures, but mine is a bit mor ...

typescript add an html element to an existing html document

I'm experimenting with creating a dynamic HTML element using TypeScript to display on a webpage. In my .ts file, my code looks like this: const displayContent = document.getElementById("display-content") as HTMLOutputElement; var displayVariable = " ...

Acquire a numerical value from a text source and increment it by one using Jquery

I have a simple task of extracting a single number from a particular div. Once obtained, I intend to increment the number by one. However, despite successfully retrieving the number, my attempts to add one to it are not working as expected. For example: ...