When using "new Array()" in a for loop it makes two seperate arrays

I have some data where I get this.
image

I want them to be in one array, like: ['static', 'lightning-rod']

await fetch(`${baseArgs}`).then(res => res.json()).then(res => {

                const data = res
                const {
                    abilities
                } = data;
                const ablength = abilities.length - 1
                for (var i = 0; i <= ablength; i++) {
                    const abilitynames = abilities[i].ability.name
                    var abilitiesarr = new Array(abilitynames)

                    callback(abilitiesarr)
                }

            })

This is the code.

In the test file its:


pokeapi.PokeApi({pokemon: 'pikachu', abilities: 'names'}, res => console.log(res))

Try the following

  • Declare abilitiesarr to be an empty array, before the for loop starts
  • abilitiesarr.push(value) inside the loop
  • Run the callback after the loop has built the array

Good luck!

4 Likes

Just to be clear, new Array() creates a new array, so everytime you run that in the for loop, it will create a new array. Following @mishavee’s instructions should solve the problem!

1 Like