Searching in an empty array using Typescript and the includes method

I want to retrieve data based on the IDs in an array. If the array is empty, I want all the data to be fetched. How can I achieve this?

selectedProductGroups: number[] = [];

products: Product[];

getProducts() {

this.generic?.Get_All("Products/Generic_Method").pipe(map(items => items.filter(items => (this.selectedProductGroups.includes(items.productGroupID) && this.selectedProductGroups.length>0)))).subscribe({
  next: (data) => { this.products = data; console.log(this.products) },
  error: (err) => { console.log(err) },
  complete: () => {
  
  }
});

}

this.products = [id=1] [id=2] [id=3] [id=4];
if(selectedProductGroups == [1,2])
{
this.products = [id=1] [id=2]
}
if(selectedProductGroups == empty)
{
this.products = [id=1] [id=2] [id=3] [id=4]
}

Answer №1

The issue with your array being empty stems from the

this.selectedUrunGrubus.length>0
condition within the filter function. Since the initial length of selectedUrunGrubus is 0, this condition will always evaluate to false.

Consider implementing a different approach. Store the filtered array in a variable and then return a ternary expression based on the result.

selectedUrunGrubus: number[] = [];

urun: Urun[];

getUruns() {

this.generic?.Get_All("Uruns/Generic_Method")
  .pipe(
    map(hizmets =>{ 
      const matches = hizmets.filter(hizmet => this.selectedUrunGrubus.includes(hizmet.urunGrubuID));
      return !!matches.length ? matches : hizmets;
    }),
    tap(urun=> this.urun = urun)
  ).subscribe();
}

Note:

  • I used double exclamation points !! to convert the length into a boolean value (since 0 is falsy)
  • Utilize tap() for managing side effects like property assignments.
  • The remaining logic within subscribe() is standard behavior, so a basic subscribe() call at the end suffices.

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

Tips for effectively hydrating Redux state in Next.js upon page refresh?

I'm experiencing an issue with hydrating user data from local storage upon app reload or page refresh. My project utilizes NextJS for the frontend, and for managing state across the application I rely on redux-toolkit and next-redux-wrapper. Upon us ...

Boosting NestJS Performance with PM2 Multiple Instances

Currently, I have a NestJS application that I typically deploy using PM2 in cluster mode with multiple instances running. One thing to note is that NestJS utilizes the Singleton pattern for its services. This is crucial for some of my features, as it allo ...

Encountering TS2339 error while attempting to append a child FormGroup within Angular framework

I'm currently working with Angular8 and facing an issue while attempting to include a child FormGroup to a form using the addControl method: this.testForm = new FormGroup({ id: new FormControl(0), people: new FormGroup({ } ...

Error: The 'hot' property is not found in the 'Module' type

Hey there! I recently started using @types/node for aws-cognito-identity provider and unfortunately encountered an error. The error message reads: Class 'Module' incorrectly implements interface 'NodeModule'. Property 'hot' ...

Fixing an HTML comment in the <title> tag in Next.js: A step-by

When working with Next.js, we encountered the following code snippet on a page: <Head> <title> Some text {title} </title> </Head> During a split second, an HTML comment resembling <!--- ---> appears momentaril ...

Having trouble clearing the value of a textfield in Ionic Angular?

Currently, I am working on a project built with Ionic and Angular. The problem I am encountering is related to user signups. Whenever an admin creates a new user, the user receives a signup link. Upon opening the link, a signup form is displayed. Although ...

Who is in charge of initializing "background" services within Angular?

I have been studying the Angular service workers documentation (https://angular.io/guide/service-worker-communications). The examples provided demonstrate services used for managing service worker lifecycle handlers such as update and failed lifecycle. My ...

Issue with ng2-toastr not displaying notifications after navigating to a different page

Currently, I am utilizing the ng2-toastr package to showcase notification messages. It functions seamlessly within the same page; however, when transitioning to a different route, the notifications do not appear on the new page. I have configured the rout ...

Is it possible to update data from the Resolver of a parent route in Angular 10?

In my application, I am facing an issue with the data retrieval process. The parent route is using a Resolver to fetch the necessary data, and there are multiple child routes dependent on this data. These child Components subscribe to the data in their ngO ...

Backend external login without password feature in .NET Core ABP 6.0 for users

Currently, I am working on a project that involves utilizing ABP 6.0 native backend (.NET Core 6 with IdentityServer) and a non-native angular frontend project with ABP installed for the static proxy tool. I am encountering difficulties in implementing Goo ...

A guide on leveraging Jest and Typescript to mock a static field within a class

While working with Typescript and a third-party library, I encountered an issue trying to write unit tests that mock out the library. Here's an example scenario: // Library.ts // Simulating a third party library export class Library { static code ...

Mastering the art of iterating through nested for loops on table rows with Angular

I want to iterate through a for loop to display response data in table rows, and I need the data values in array format. Can you please guide me on how to achieve this with the code provided below? HTML file <div class="row"> <f ...

There is no assigned value in scope for the shorthand property. You must either declare one or provide an initializer

I'm just starting out with TypeScript. Encountering the error 'No value exists in scope for the shorthand property 'firstName'. Either declare one or provide an initializer.' while using Prisma with Next.js to create a new user in ...

What could be causing production build to not recognize .env variables within Node.js (TypeScript)?

I'm encountering a problem with my Node.js backend project coded in TypeScript. Everything is running smoothly locally, and the environment variables defined in the .env file are loading correctly thanks to the dotenv package. However, once I build th ...

Tips for maintaining a healthy balance of tasks in libuv during IO operations

Utilizing Typescript and libuv for IO operations is crucial. In my current situation, I am generating a fingerprint hash of a particular file. Let's say the input file size is approximately 1TB. To obtain the file's fingerprint, one method involv ...

Leveraging editor.action.insertSnippet from a different plugin

I am attempting to enhance the functionality of VS Code by adding buttons to the status bar that automatically insert code snippets. I am utilizing this Extension for this purpose. Additionally, I have configured keybindings in my keybindings.json file whi ...

The solution to automatically delete orphaned rows in TypeORM

Having a one-to-many relationship in TypeORM, I am interested in deleting rows from the many side of the connection rather than just unlinking them and leaving orphaned entries. Can anyone suggest a way to achieve this since the proposed feature for it w ...

Error: Angular 6 resolve consistently returns undefined

Seeking to implement my service for retrieving values from the database server and displaying them onscreen, I have set up a resolver for the service since the database can be slow at times. However, no matter what I try, the data received through this.ro ...

Tips for ensuring the reliability of unit tests when testing an OnPush component in Angular with fixture.detectChanges()

I developed a project where I implemented a Component that fetches data asynchronously from a service and displays it to the user. The Component code is as follows: @Component({ changeDetection: ChangeDetectionStrategy.Default, selector: 'test-co ...

Installing Optional Dependencies with NPM

In our shared library, we have streamlined the bootstrapping code installation through Bootstrap for most users who utilize plain Javascript on the front end. However, there are also a few individuals who prefer to work with Typescript. Could it be possib ...