In TypeScript, the indexof method is not available when filtering based on numbers

When attempting to filter the month value in a dropdown, I encountered an error stating that indexOf() is not a function. Here is the code snippet:

@Pipe({
    name: "monthFilter",
})
export class MonthStatusPipe implements PipeTransform {
      transform(array: any[], query: number): any {  
        console.log("query", query);
        if (query) {
            return _.filter(array, row => row.LicenseMonth.indexOf(query) > -1);
        }
        return array;
    }
}

Are there any alternative methods to filter dropdowns based on values?

Here is a sample of my JSON data:

{
    "BusinessId": 1549,
    "OrganizationNumber": "992060867",
    "CompanyName": "Litra Containerservice AS ",
    "Address": "Industrigata 62",
    "Zipcode": "2619 Lillehammer",
    "Mobile": "98238925",
    "Telephone": "66789485",
    "ConnectedTo": "Admin",
    "ConnectedToId": "123",
    "HSEManager": "Marina Magerøy",
    "BusinessContact": "Lars Andre Skogstad",
    "ContactMobile": "48499613",
    "BusinessContactTelephone": "45283769",
    "NoOfEmployees": "15",
    "Status": "Active",
    "ModifiedOn": "2016-10-01T23:55:01.033",
    "LicenseMonth": 10,
    "Category": "Godstransport på vei"
  },

Answer №1

The reason for this is that the variable LicenseMonth is actually stored as a numeric value.

To resolve this issue, you can use the following code:

@Pipe({name: 'monthFilter'})
export class MonthStatusPipe implements PipeTransform {
      transform(arr: any[], num?: number): any {
        return typeof num !== 'undefined' 
           ? arr.filter(e => e.LicenseMonth === num)
           : arr;
    }
}

Consider a more generic approach instead of creating a pipe for a specific field.

You can implement a more universal solution, such as:

<p>{{ rows | filterBy: ['LicenseMonth']: 42  }}</p>

You have the option to create your own version of this solution or utilize a library containing various helpful pipes.

ngx-pipes: https://github.com/danrevah/ngx-pipes

Information on the filterBy pipe: https://github.com/danrevah/ngx-pipes#filterby

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

defaultValue cannot be used with createContext

Currently, I am endeavoring to establish a context utilizing the createContext method from the react API: import React, { useState, createContext } from 'react'; export const MovieContext = createContext(); export const MovieProvider = (props) ...

What is the best way to monitor parameter changes in a nested route?

I need assistance with managing routes const routes: Routes = [ { path: 'home', component: HomeComponent }, { path: 'explore', component: ExploreComponent, children: [ { path: '', component: ProductListC ...

Is there a way to showcase all components on a single page in Angular 2 without needing to bootstrap them in appModule?

Is there a way to showcase all my Angular 2 components on one page without having to bootstrap them individually in AppModule.ts? I'm looking for a solution using router-outlet or parent-child relationships. Any guidance on how to achieve this after s ...

"Encountering issues with ngrx store selector when importing app from a custom

My Angular library includes a store implementation and is distributed as an NPM package, used in various Angular applications. I encountered an error when attempting to use a ngrx store selector exported from the library in a different Angular project: ...

Using Angular: filtering data streams from a date range observable object

I have a piece of code that seems to be functioning correctly, but I can't shake the feeling that it might just be working by chance due to an undocumented feature. I'm torn between questioning its validity or accepting that it is indeed designed ...

Troubleshooting a useContext error in Next.js with TypeScript

I've been working on an app using next.js for the frontend, and I encountered an issue while trying to stringify an object. Here's a snippet of the error message: Argument of type '{ auth: dataObject; }' is not assignable to parameter o ...

Is there a way to define one type parameter directly and another type parameter implicitly?

I am currently utilizing a UI-library that offers an API for constructing tables with a structure similar to this: type Column<Record> = { keys: string | Array<string>; render: (prop: any, record: Record) => React.ReactNode; } The l ...

Using both <router-outlet> and <div ng-view> in AngularJS and Angular for routing simultaneously

Within my app component (originally an Angular 2 component but downgraded for index.html), I have the following code: <router-outlet></router-outlet> <div ng-view></div> I followed the instructions in the "Dividing routes betw ...

Tips for modifying JSON response using a function

When I call the function buildFileTree, I store its response in a constant variable called data. const data = this.buildFileTree(dataObject, 0); The value of dataObject is: const dataObject = JSON.parse(TREE_DATA); And the content of TREE_DATA is: cons ...

What is the best way to verify a numerical input in a React component?

When I use the return statement, I attempt to validate a number and if it's not valid, assign a value of 0. However, this approach doesn't seem to be working for me. Is there an alternative method to achieve this? return ( <Input col ...

Ways to retrieve the quantity of a particular value within an object using TypeScript

I'm inquiring about how to retrieve the number of a specific value within an object using TypeScript. Here is the structure of the object: obj : TestObject = { name: "test", street: "test" subobj1: { status: warning, time: ...

Utilizing Database values in .css files with Vue.js and TypeScript

I am currently working on extracting a color value from the database and applying it to my external .css files. I have searched extensively online but haven't found a satisfactory solution yet. Here is the JavaScript code snippet: createBackgroundHead ...

What is the best way to add a table header with a column of interactive buttons in Angular?

I am currently utilizing Angular and have created a table displaying important data. The first column features checkboxes for individual selection or selecting all. Following the checkbox column are additional columns of data for updating/deleting informat ...

Bidirectional data binding in Angular 2 for the class attribute

Utilizing twitter bootstrap tabs, I aim to monitor the application of the active class on the li tag as users switch between different tabs. My objective is to control tab activation through custom buttons by modifying the class attribute to activate direc ...

Get rid of the strange border on the material dialog

I am struggling with the Angular material 6 dialog component as it is displaying a strange border. I have attempted to remove it using the code below, without success. Interestingly, when I apply the style inline in the browser, it works fine. Any suggesti ...

Next.js is failing to infer types from getServerSideProps to NextPage

It seems like the data type specified in getServerSideProps is not being correctly passed to the page. Here is the defined model: export type TypeUser = { _id?: Types.ObjectId; name: string; email: string; image: string; emailVerified: null; p ...

HTTP POST request is being blocked due to cross-origin request

My angular client app is sending http requests to a .NET core web API, but I'm encountering a CORS error even though I have enabled CORS. Interestingly, GET requests to my SearchController work fine without any issues, but when it comes to sending a P ...

Tips for accessing the app instance within a module in Nest.js

Currently, I am involved in a project that relies on multiple Nest repositories, approximately 4 in total. Each repository must integrate logging functionalities to monitor various events such as: Server lifecycle events Uncaught errors HTTP requests/resp ...

Creating a typescript object shape without an index signature involves specifying the exact properties

I have a query regarding a potential design gap in TypeScript. Consider a function that accepts objects meeting a specific interface: interface Params { [key: string]: string | number | boolean | undefined | null; } This interface specifies that the k ...

Assigning union values to an object array: a guide for Typescript

When working with union typed values in an object array, how should the setState() function be implemented? enum SomeStateEnum { IsRunning, Name, } type PersonState = { [SomeStateEnum.IsRunning]: boolean; [SomeStateEnum.Name]: string; }; const st ...