Eliminate item from nested array when the array is devoid of elements in Typescript

If the nested array is empty and I want to remove the object, how can I achieve this? For example, consider the following array:

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

      ]
    }]

In this case, we have an empty array:

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

To remove this object and update the array to:

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

Answer №1

To remove empty groups, you can utilize the filter method like so:

pokemonGroups = pokemonGroups.filter(group => group.pokemon.length !== 0);

Answer №2

To remove empty arrays within your array, you can loop through the array and use array.splice() method. Here's an example in JavaScript:

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)

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

Finding the common elements between arrays of objects in PostgreSQL

Suppose there are rows in my database with a JSONB column containing an array of items like this: [ {"type": "human", "name": "Alice"}, {"type": "dog", "name": "Fido"}, { ...

Integrate a JS file into my Angular 4 project

For one of my components, I am looking to implement a specific effect: https://codepen.io/linrock/pen/Amdhr Initially, I attempted to convert the JavaScript code to TypeScript, but faced challenges. Eventually, I decided to directly copy the JS file from ...

Sending data from parent component to change MUI Button color (React with typescript)

Recently, I've been integrating MUI (v5) into a create-React-App with typescript. I have a custom theme set up as well. My goal is to develop a MyButton Component that accepts a buttonType prop (of type string), which corresponds to my theme.palette, ...

What is the process for connecting custom transformers to a compiler host?

My custom TypeScript watcher is set up like this: const compilerHost = typescript.createWatchCompilerHost(config.fileNames, config.options, typescript.sys, undefined, reportDiagnostic) typescript.createWatchProgram(compilerHost) I am trying to integrate ...

Issue with default date not functioning in Primeng's p-calendar module

I'm having trouble setting a default date in the datepicker. I attempted to use the defaultDate property of p-calendar, here's what I did: <p-calendar placeholder="mm/dd/yyyy" name="deadline" required [(ngModel)]="deadline" #deadline="ngMo ...

Refrain JavaScript - sift through an array of objects based on the values of a primitive array in linear time

I've got an array of objects that looks like this: [{ itemType: 'bottle', itemId: '111' }, { itemType: 'bottle', itemId: '222' }, { itemType: 'bottle', ...

What is the best way to transfer the userId from the browser to protractor?

Using *ngFor in my angular2 component to render users has been successful. <ul> <li *ng-for="let user of users"> <input [(ng-model)]="user.name"> <button (click)="remove(user._id)">Remove</button> ...

Explore all user-defined properties of a specified type using the TypeScript Compiler API

Consider the following model structure: interface Address{ country: string; } interface Author{ authorId: number; authorName:string; address: Address; } interface Book{ bookId:string; title: string; author : Author; } I want to iterate th ...

Having trouble locating the module for my custom TypeScript module

Exciting news! I have recently released a new TypeScript-based module on the NPM registry, called ooafs. However, when attempting to install and import it into another TypeScript project, an error pops up in VSCode stating: Cannot find module 'ooafs&a ...

Error encountered while installing Material UI in Next.js with TypeScript and pure JavaScript configurations

I'm brand new to React and Next.js, so please forgive me for asking what may seem like a silly question. I'm attempting to install Material UI in a fresh Next.js application that I created using "npx create-next-app@latest". I've been refere ...

Defining the limits of an array in Python

Is there a way to set a limit in an array in Python? Here's what I have tried so far: answerBox = [] * 10 #This will initialize the array with 10 empty elements. I want to know how to make sure that if an answer exceeds the 10 element limit, it prin ...

What could be causing the "serviceName error: No provider found" message to appear?

Currently, I am working on sharing a value between two components in Angular. The setup involves a ProjectView component that renders a ProjectViewBudget component as a "child" (created within a dynamic tab component using ComponentFactoryResolver) with th ...

What is the best way to incorporate padding into an Angular mat tooltip?

I've been attempting to enhance the appearance of the tooltip dialog window by adding padding. While adjusting the width and background color was successful, I'm encountering difficulties when it comes to styling the padding: https://i.sstatic.ne ...

The type 'MouseEvent<HTMLButtonElement, MouseEvent>' cannot be matched with the type 'boolean'

Just starting out with TS and running into a problem that TS is pointing out to me. Error: Type '(x: boolean) => void' is not compatible with type '(e: MouseEvent<HTMLButtonElement, MouseEvent>) => void'. Parameters ' ...

How to anticipate an error being thrown by an observable in RxJS

Within my TypeScript application, there exists a method that produces an rxjs Observable. Under certain conditions, this method may use the throwError function: import { throwError } from 'rxjs'; // ... getSomeData(inputValue): Observable<s ...

What is the best way to run ng test for all components within a sub module of an Angular application?

In my Angular application, I have defined the app module as follows: app.module.ts export class AppModule {} I am able to execute tests using ng test MyApp Within this application, I also have multiple modules set up like so: my-one.module.ts / my-oth ...

I obtained the binary tree output in the form of an object. How can I extract the values from this object and store them in an array to continue working on

Issue Statement In this scenario, you have been presented with a tree consisting of N nodes that are rooted at 1. Each node in the tree is associated with a special number, Se. Moreover, each node possesses a certain Power, which is determined by the count ...

Conditional types allow the function parameter type to be determined based on the type of another parameter

Here: function customFunction<T extends boolean> (param1: T, param2: T extends true ? number[] : number) { if (param1) { let result: number[] = param2; // Type 'number' is not assignable to type 'number[]'.(2322) } } ...

Updating the page dynamically in React/Redux by making API calls based on user submissions

My current task involves calling an API with Redux, triggering the call based on a form submission. If the query is empty, it should return all lists; otherwise, it should only return lists that match the query. // List.tsx import React, { useEffect, useS ...

The ng command seems to be malfunctioning when executed from a separate directory

After selecting a different folder for my new angular project, I encountered an error every time I tried to run an ng command: 'ng' is not recognized as an internal or external command, operable program or batch file. I attempted to resolve ...