Home > OS >  Loop until find an array empty in Javascript
Loop until find an array empty in Javascript

Time:04-18

I'm trying to find a solution to make a loop (Javascript) until the array of object is empty. Here the object that I want to use :

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

I would like to loop until to find the variable evolves_to empty. and in each loop using the species.name, to list the evolution, in my case : nidoran-f -> nidorina -> nidoqueen

I can not find yet a good way to do it. A bit lost. Thank you for your help ;)

CodePudding user response:

You can use 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)

Or to collect values in an array:

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)
   console.log(arr.join(" -> "))
   return
  } else {
    arr.push(obj.species.name)
    traverse(obj.evolves_to[0])    
  }
}

traverse(chain)

  • Related