The Angular filter fails to remove elements from the list

I have implemented a filter function to remove objects from an array, but I am facing an issue. Challenge: Despite using the filter function, the elements are not being removed from the array as expected. Why are these objects still present in the array after filtering them out?

async filterPspDeliveries(pspDeliveryList: PspDelivery[]){
    try {
        return pspDeliveryList.filter(pspDelivery => pspDelivery.packageList.length > 0);
    } catch(e) {
      console.log(e);
    }
}

The filter function is called within the same class here:

for (let psp of pspList){
    let tmpDeliveryList = await this.filterPspDeliveries(psp.deliveryList);
    psp.deliveryList = tmpDeliveryList;
}

Note: My intention is to eliminate deliveries that do not have a package list associated with them.

Your assistance on this matter would be greatly appreciated.

Answer №1

There is no need for a try-catch block in this scenario since the .filter function will always succeed. Consider using the following code instead:

function filterPspDeliveries(pspDeliveryList: PspDelivery[]) {
    return pspDeliveryList.filter(pspDelivery => pspDelivery.packageList && pspDelivery.packageList.length > 0);
}

Answer №2

Referencing information from this source:

The await operator serves to pause execution until a Promise is settled. It is restricted to use within an async function.

An issue arises when you await a function that does not yield a Promise. Rather, the function async filterPspDeliveries is producing an array of PspDelivery.

Furthermore, there is no necessity for the async identifier in the filterPspDeliveries method since no awaiting occurs.

To resolve this matter, two solutions are proposed:

Solution 1

Omit the await keyword:

 for(let psp of pspList){
      let tmpDeliveryList =  this.filterPspDeliveries(psp.deliveryList);
      psp.deliveryList = tmpDeliveryList;
    }

Solution 2

Retain the await keyword by returning a promise within filterPspDeliveries:

  filterPspDeliveries(pspDeliveryList: PspDelivery[]): Promise<PspDelivery[]> {
    try {
      return new Promise(resolve => {
        let result = pspDeliveryList.filter((pspDelivery) => {
          return (pspDelivery.packageList.length > 0);
        })
        resolve(result);
        return;
      });
    } catch (e) {
      console.log(e);
    }
  }


for(let psp of pspList){
      let tmpDeliveryList = await this.filterPspDeliveries(psp.deliveryList);
      psp.deliveryList = tmpDeliveryList;
    }

You can observe the functionality of both solutions here.

Answer №3

What are your thoughts on implementing the following change:

async filterPspDeliveries(pspDeliveryList: PspDelivery[]){
    try{
      return pspDeliveryList.filter((pspDelivery) => pspDelivery.packageList && pspDelivery.packageList.length > 0);
    } catch(e) {
      console.log(e);
    }
  }

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

What sets apart the ? operator from incorporating undefined in the type declaration?

Can you explain the distinctions among these options? type A = {a?: string} type A = {a: string | undefined} type A = {a?: string | undefined} In what scenarios would one be preferred over the others? For more information, visit: https://github.com/mic ...

Specify that a function is adhering to an interface

Is there a way in Typescript to ensure that a function implements a specific interface? For example: import { BrowserEvents, eventHandler, Event } from './browser-events'; export function setup(){ const browserEvents = new BrowserEvents(); b ...

What is the best way to incorporate an image into the canvas element and then use it as a drawing surface?

I have been searching for solutions on various platforms, but I'm having trouble finding ones that work specifically with Ionic and Angular. One major issue I'm facing is trying to copy an image to the canvas. No matter what I try, I can't ...

Issue with missing support-v4.jar in Nativescript Angular

I'm currently testing out a groceries sample using Nativescript with Angular and Typescript. I followed the instructions from this link Encountering the following error: FAILURE: Build failed with an exception. * What went wrong: An issue occurre ...

How to retrieve data from a nested object in Angular templates

I am working with a "post" object that has an "author" property, linking each post to the author who created it. The "author" property is a nested "user" object with a "name" property. My goal is to access the "name" of the user associated with a specifi ...

Angular 4: Modifying the URL without the Component being Displayed

I'm currently facing an issue where I am attempting to link a component from one component using routerLink = "selected" const routes: Routes = [ { path: '', children: [ { path: 'account&apo ...

Is it possible to dynamically change an ngModel value directly from the component?

I'm currently immersed in an Angular project and my initial file setup was like this: dog.ts: export interface Dog { name: string; age: number; breed: string; } dog.component.ts: import { Dog } from '../dog'; @Component({ //setup ...

Looking to effortlessly move and arrange items with ng2-drag-drop in Angular 2?

I have encountered a problem with the ng2-drag-drop library. I am trying to drag and drop items from one div to another, and then freely move the dropped item within the droppable area. One issue I'm facing is that when I drop my draggable item in th ...

What is the best way to retrieve information from a json file using axios in a React project?

I'm having trouble retrieving JSON data. { ID string `json:"id"` Amount int `json:"amount"` Month string `json:"month"` PayFailed bool `json:"pay_failed"` } I’ve written the foll ...

Display loader during data retrieval in Angular 2

In my loader.component.ts file, I have defined the selector as <app-loader>. The <app-loader> tag is located in the main-component.html file and is displaying correctly. <app-loader *ngIf="!showLoader === true"> I want the loader to on ...

I am encountering a strange error in the console when trying to implement a custom navigation system tailored to each user using the core UI Angular

An error occurred at line 33 in the AppSidebarNavItemsComponent.html file. The error message states: "ERROR TypeError: Cannot read property 'length' of undefined". Here is the sequence of events leading up to this error: - The createUrlTree funct ...

What is the best way to alter the Date format in Typescript?

Within my response, the field createdate: "2019-04-19T15:47:48.000+0000" is of type Date. I am looking to display it in my grid with a different format such as createdate: "19/04/2019, 18:47:48" while maintaining its original data type. To achieve this, I ...

Unable to access res.name due to subscription in Angular

Right now, I am following a tutorial on YouTube that covers authentication with Angular. However, I have hit a roadblock: The code provided in the tutorial is not working for me because of the use of subscribe(), which is resulting in the following messag ...

Angular 13: Opt for Just-in-Time compilation instead of Ahead-of-Time when using ng-

Starting from Angular 9, AOT compilation is enabled by default. I attempted to run the application in JIT mode by using the option "--aot=false", which resulted in an error stating "Unknown option --aot". Furthermore, when trying to disable AOT at startu ...

While the Angular application in VS Code may be successfully compiled, the most recent changes may not appear in the browser

Lately, while working on my angular application using Visual Studio Code as my code editor, I encountered two unexpected issues that have been causing me trouble. After running the command ng serve in the terminal, I receive a √ Compiled successfully. ...

Retrieve items from the <ng-content></ng-content> within the corresponding component in the TypeScript file

I'm facing an issue where I can't retrieve elements from ng-content within the same component. Here is my setup: Component HTML <div> <ng-content #action></ng-content> <app-comp2></app-comp2> </div> Component ...

Is it possible to utilize Webpack 5's ChunkGroup API with several entries?

I am encountering an error message when attempting to upgrade from Webpack 4 to Webpack 5. The error states: Module.entryModule: Multiple entry modules are not supported by the deprecated API (Use the new ChunkGroup API) I have searched for information o ...

Experiencing a RepositoryNotFoundError in TypeORM, although I am confident that the repositories are properly registered

I am creating a new application using Next.js + TypeORM and encountering an issue with the integration. RepositoryNotFoundError: No repository for "User" was found. It seems like this entity is not registered in the current "default" connection? Althoug ...

Leveraging the Typescript Compiler API for transforming a typescript document

I am currently exploring the Typescript Compiler API to develop a tool that merges typescript files. I am curious if there is a way to: Modify the AST after parsing a .ts file. Convert the modified AST back into a .ts file. I have reviewed the documenta ...

Error building Angular module occurred while executing the project

Recently, I got an Angular template from this site: After successfully running npm install, I encountered an error when trying to run ng serve: ./src/styles.scss - Error: Module build failed (from ./node_modules/mini-css-extract-plugin/dist/loader.js): Mo ...