How to effectively manage blank strings, null values, and undefined values when filtering in Angular

I have created a custom pipe to filter values within an array of objects. While the basic functionality is in place, I am encountering difficulties when handling empty strings, nulls, and undefined values. When any of these values are passed to the pipe, the expected behavior is for all values from the array to be returned. The pipe is designed to filter based on an object's property, as well as filtering against an array of primitive string or numeric values. I have written several test cases, most of which are passing successfully except for those related to specific scenarios mentioned in this post.

custom-filter.pipe.ts

export class CustomFilterPipe implements PipeTransform {

  transform(data: any[], arguments: any[] | any): any[] {
    const propToFilter = arguments[1]; // property to filter on
    const userInput = arguments[0] || arguments; // user input for filtering
    return data.filter((item: any) => {
      if (item[propToFilter] && userInput !== ('' || undefined || null))
        return item[propToFilter].toString().includes(userInput);
      else if (userInput === ('' || undefined || null)) // addressing the "empty" cases
        return (item[propToFilter].toString().includes(item) || item.toString().includes(item));
      else return item.toString().includes(userInput);
    });
  }

}

failing test case

it('should return a list of all matches if no user input is provided', function () {
    const items = [
      {value: 'apple'},
      {value: 'banana'},
      {value: 'cherry'},
      {value: 'date'}
    ];
    const filterProp = 'value';
    const numbers = [10, 20, 30];
    let output = pipe.transform(items, ['', filterProp]);
    expect(output).toEqual(items);
    output = pipe.transform(items, [null, filterProp]);
    expect(output).toEqual(items);
    output = pipe.transform(items, [undefined, filterProp]);
    expect(output).toEqual(items);
    output = pipe.transform(numbers, '');
    expect(output).toEqual([10, 20, 30]);
    output = pipe.transform(numbers, null);
    expect(output).toEqual([10, 20, 30]);
    output = pipe.transform(numbers, undefined);
    expect(output).toEqual([10, 20, 30]);
  });

The expect statement in the failing test case is currently returning an empty array instead of the expected full list of values (i.e. items or numbers).

Answer №1

It appears that the issue lies not with your test, but rather with how you've implemented it.

Your current else if statement's condition always results in false. Essentially, you're checking for minVal === false, which will never be true.

To resolve this problem, simply update it to read as follows: else if (!minVal) { ... }.

Additionally, the initial condition also needs adjustment; it should now be

if (item[filterProperty] && minVal)
.

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

Ways to modify the information retrieved from JSON?

I've integrated the OMDB api (Online Movie DB) into my project. The interface I created is returning the expected data types, with data being returned as {Search: Array(10), totalResults: "31", Response: "True"} when using the http get method. The spe ...

Increasing the number of service providers in Angular2-4 directives

Is there a way to apply both * to a string? Below is the code snippet I am working with: <a class="sidenav-anchor" *ngIf="!item.hasSubItems()" md-list-item md-ripple [routerLink]="[item.route]" routerLinkActive="active" [routerLinkActiveOptions]="{ex ...

Exploring Angular Material's Autocomplete feature and staying updated with incoming data changes

https://material.angular.io/components/autocomplete/examples export class AutocompleteAutoActiveFirstOptionExample implements OnInit { myControl = new FormControl(); options: string[] = ['One', 'Two', 'Three']; filtered ...

Can you use TypeScript to define generic React functional components?

I am looking to add annotations to a generic in a React functional component like the following: import React, {useEffect, useState} from "react"; interface PaginatedTableProps{ dataFetcher: (pageNumber: number) => Promise<any>, columnNames: ...

The takeUntil function will cancel an effect request if a relevant action has been dispatched before

When a user chooses an order in my scenario: selectOrder(orderId): void { this.store$.dispatch( selectOrder({orderId}) ); } The order UI component triggers an action to load all associated data: private fetchOrderOnSelectOrder(): void { this.sto ...

What are some ways to customize formControlNames in Angular reactive forms?

Is there a way to customize the formControlName in Angular forms? I need to be able to toggle check-boxes on and off based on certain values within a nested object array. Here is an example of what the HTML code might look like: <span class="col-md-2" ...

Utilizing Angular code across various components for seamless integration

I am facing a dilemma with my menu placement in the component header. I have various divs in the main component that I need to toggle visibility on with the right menu button. However, splitting my code into different components seems to disrupt this funct ...

How do I repeatedly display an HTML element using a loop in Typescript?

As a newcomer to Typescript, I am attempting to create a function that generates multiple buttons based on the data stored in an array. Initially, I tried using a for loop like this: splitLabels(Array: any){ if (typeof Array != "undefined& ...

Error Encountered: Unexpected Identifier in Angular 7 External jQuery Plugin

Struggling to convert a jQuery template to Angular7, I'm facing an issue with loading .js files from the assets folder in the original template to make it functional. Upon starting the application with: ng serve, I encounter the following error in th ...

Exploring how to iterate through an object to locate a specific value with TypeScript and React

I am looking to hide a button if there is at least one order with status 'ACCEPTED' or 'DONE' in any area or subareas. How can I achieve hiding the "Hide me" menu item when there is at least one area with orders having status 'ACCE ...

Angular Rick and Morty API Integration

I am working on iterating through objects retrieved from this URL: () to display them in a gallery of cards using *ngFor 1 This method is the only one I have found to render my data, but when I scroll down, it updates the URL for the new call 2 The issue ...

Adjusting the focal point of a brochure on open street map

I am currently working on initializing a map in an Angular application using leaflet with openstreetmaps. I have set the center of the map so that it is displayed to the user when they open the site. However, I am now trying to figure out how to dynamica ...

unexpected issue with npm package installation

I am currently exploring NPM and angular2, and attempting to create my own NPM package for local installation. I was able to successfully create the package (test-package-0.0.1.tgz) which includes: ├── .npmignore ├── README.md ├── LICENS ...

Uncertainty surrounding the extent of a button's scope within an Angular application

(click) event in one instance of a component is causing the function in another instance to be triggered unexpectedly. I am having trouble describing this issue. For reference, I have included a working example on stackblitz. When clicking on both buttons ...

Combine the array elements by date in Angular, ensuring no duplicates are present

How can array data be merged based on the date while avoiding duplicates? See the code snippet below: [ { date: [ '2019-12-02 08:00:00', '2019-12-03 08:00:00' ], upload:["47.93", "47.46", "47.40", "47.29" ], download: ["43.90", ...

Utilizing TypeScript to import and export modules under a single namespace

Have a look at this query that's quite similar to mine: https://github.com/Microsoft/TypeScript/issues/4529 Consider the following code snippet: //exported imports export {ISumanOpts, IGlobalSumanObj} from 'suman-types/dts/global'; export ...

The given 'FC<ComponentType>' type argument cannot be assigned to the 'ForwardRefRenderFunction<unknown, ComponentType>' parameter type

Currently, I am using react in conjunction with typescript. Within my project, there are two components - one serving as the child and the other as the parent. I am passing a ref to my child component, and within that same child component, I am binding my ...

Tips for detecting when the enter key is pressed using Typescript

How can I detect when the enter key is pressed in a form element in Typescript by attaching a keypress event? Below is the code from my index.ts file: const search_field = document.querySelector('#search-field'); search_field?.addEventListener(& ...

Unlocking Security in Angular 2

I am struggling with the issue of security in Angular 2. I am attempting to calculate the width of a span element within an ngfor loop: <span style="width:updateStyle({{ ((date | amDifference : item.startdate : 'minutes' :true)/item.duratio ...

Incorporating server-side HTML content into a div using Angular 2

I have a series of HTML files stored on my server. Examples include: Now, I am attempting to include these files into a <div> in my Angular 2 v4 app. For instance: component.ts public changePage(name: string) { switch (name) { case 'int ...