0

How can I remove the object if the nested array is empty. Like I have an array:

pokemonGroups = [
    {
      name: 'Grass',
      pokemon: [
        'bulbasaur-0', 'Bulbasaur', 'oddish-1','Oddish','bellsprout-2', 'Bellsprout'
      ]
    },
    {
      name: 'Water',
      pokemon: [

      ]
    }]

So In this we have an empty array

{
   name: 'Water',
   pokemon: []
}

So I want to remove this object and my array should be like:

pokemonGroups = [
    {
      name: 'Grass',
      pokemon: [
        'bulbasaur-0', 'Bulbasaur', 'oddish-1','Oddish','bellsprout-2', 'Bellsprout'
      ]
    }
 ]

2 Answers 2

1

You can use filter:

pokemonGroups = pokemonGroups.filter(group => group.pokemon.length != 0);
Sign up to request clarification or add additional context in comments.

Comments

1

You can iterate your array and use array.splice()

var pokemonGroups = [{
    name: 'Grass',
    pokemon: [
      'bulbasaur-0', 'Bulbasaur', 'oddish-1', 'Oddish', 'bellsprout-2', 'Bellsprout'
    ]
  },
  {
    name: 'Water',
    pokemon: [

    ]
  }
]

for (var i = 0; i < pokemonGroups.length; i++) {
  if (pokemonGroups[i]['pokemon'].length == 0) {
    pokemonGroups.splice(i, 1);
  }
}

console.log(pokemonGroups)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.