Angular - Implementing filter functionality for an array of objects based on multiple dropdown selections

I am currently working on filtering an array of objects based on four fields from a form. These four fields can be combined for more specific filtering.

The four fields consist of two dropdowns with multiple selection options and two text boxes.

Upon clicking a button, the data should be filtered according to the selected fields using the following method:

filterData(form: NgForm) {
    // Code for filtering data goes here
}

Currently, the filtering works correctly for the text box filters (Description and File Name). Users can select one or both boxes to filter the data accurately.

My challenge lies in incorporating the multiple selection filters (Type and Company). Below is an example object representing all selected filters for the search:

arrFilter = [
   {
      "field":"type",
      "value":[
         "Type1",
         "Type2",
         "Type3",
         "Type4"
      ]
   },
   {
      "field":"company",
      "value":[
         "CompanyA",
         "CompanyB"
      ]
   },
   {
      "field":"description",
      "value":"Test"
   },
   {
      "field":"name",
      "value":"Test.txt"
   }
]

Any suggestions on how to incorporate the multiple selection filters effectively? Your input is appreciated. Thank you.

Answer №1

To handle the logic correctly, determine whether the value of filter.value is an array or not.

Consider using this approach:

const results = this.gridValueClone.filter(data => 
    arrFilter.every(filter =>
        Array.isArray(filter.value)
            ? filter.value.includes(data[filter.field])
            : filter.value === data[filter.field]
    )
);

The use of forEach() in the filter callback may be confusing, so I removed it and replaced it with a call to every().

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

The ts-node encountered an issue with the file extension in this message: "TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension

When using ts-node, I encountered the following error: $ ts-node index.ts TypeError [ERR_UNKNOWN_FILE_EXTENSION]: Unknown file extension ".ts" for /home/projects/node-hddds8/index.ts I attempted to remove "type": "module& ...

Developing an object using class and generic features in Typescript

I am currently working on creating a function or method that can generate sorting options from an array. One example is when using Mikro-ORM, where there is a type called FindOptions<T> that can be filled with the desired sorting order for database q ...

Implementing multiple modules within a shared parent route in Angular

Currently, I am seeking a method to load multiple modules under the same path in Angular. Let's say I have three modules: AModule, BModule, and CModule, each with its own RouterModule.forChild call. My goal is to combine these modules under the route ...

The table is failing to display the values contained within the array

My users list is successfully retrieved from the API and I can see the data in my console. However, when I attempt to map it and display it as a table, it doesn't seem to work as expected. This is the component I'm working with: interface IUser { ...

Unleashing the Power of RxJS with OR Conditions

I am working with two Observables. For instance, I am waiting for either an HTTP POST call or a WebSocket call to return so that I can proceed. Once either call returns, I need to verify the information until a certain condition is met. In the following e ...

Issue with PrimeNG dropdown where selected option gets reset when bound to interface property

Here is how I have implemented the p-dropdown: <p-dropdown name="taxOptions" [options]="taxOptions" [(ngModel)]="purchaseInvoiceDetail.tax"></p-dropdown> The values for the taxOptions property are set like this: this.taxOptions = [ { l ...

How can I transfer data between methods within Angular?

Help Needed: I have a service file with two methods, each having its own API. I want to call the getData method within the deleteData method. Can anyone guide me on how to achieve this? .service.file getData(): Promise<PagedResult<Sites>> { ...

Exploring Manipulation of M:N Associations in Sequelize

I have set up a sequelize schema using postgre DB export const Commune = sq.define("commune",{ codeCommune: { type: DataTypes.STRING(5), allowNull: false, primaryKey: true }, libelleCommune: { type: ...

Seeking assistance with TypeScript promises

Just starting out with typescript and nodejs, but I've got to tackle some issues in the typescript code. I'm looking to execute an ECS one-off task using Pulumi. I have the documentation on how to run the task from the taskDefinition, which can ...

What can we achieve using typename and nested types in a Typescript generic function?

I've been exposed to numerous tricks, but I seem to be struggling with this particular puzzle; therefore, any assistance from someone with more experience in TS would be greatly appreciated. My subscribe() function requires: Message type in the form ...

Issue with res.redirect not properly redirecting to https site

After reading numerous posts with the same title, I have tried several suggestions but none of them have worked. In my Angular2 app with a server API, I am looking to automatically redirect in production if it's not secure. The code below is the fir ...

Unable to detect tsc after installing globally within Windows Sandbox

I followed the instructions provided here to install TypeScript globally. npm install -g typescript After installing both inside vscode and outside, I encountered an issue where tsc --version does not work and shows 'tsc is not recognized'. Int ...

Importing configuration file in CRA Typescript with values for post-deployment modifications

I am currently working on a React app that utilizes Create React App and Typescript. My goal is to read in configuration values, such as API URLs. I have a config.json file containing this data, here's a sample snippet with placeholder information: { ...

How to retrieve the current route name or URL in AngularDart5

Exploring the OnActivate feature in Angular docs, I am attempting to utilize it to dynamically update the UI based on the current route. @Component( selector: "blah", template: """blah""", directives: const [routerDirectives]) class Blah ext ...

Customizing the choices for an ActionSheet on Ionic 2 on the fly

After making a GET request, I receive JSON data containing an array of options with id, style, and name for each element. I need to dynamically populate the options in my ActionSheet within my Ionic 2 app based on this API response. The ActionSheet is fu ...

Is there a way to transfer a variable from Angular 2 Frontend Express JS to an Angular 2 component?

After conducting thorough research, I have made specific modifications to my code. However, I am encountering some errors in my console that I cannot seem to resolve. Despite following a tutorial step by step. Your assistance would be highly valued as I a ...

How can we leverage the nullish coalescing operator (`??`) when destructuring object properties?

When working with ReactJS, I often find myself using a common pattern of destructuring props: export default function Example({ ExampleProps }) { const { content, title, date, featuredImage, author, tags, } = ExampleProps || {}; ...

The combination of UseState and useContext in React Typescript may lead to compatibility issues

I attempted to integrate the context API with the useState hook but encountered difficulties when using TypeScript. First, let's create App.tsx: const App = () => { const [exampleId, updateExampleId] = useState(0); return ( <div> ...

Unable to bring in CSS module in a .tsx file

I am currently working on a basic React application with TypeScript, but I am encountering difficulty when trying to import a CSS file into my index.tsx file. I have successfully imported the index.css file using this method: import './index.css&apo ...

The problem arises when the type of a Typescript literal union becomes more specific within React children

Currently, I am in the process of converting our React/Redux project to TypeScript and encountering a challenge with TypeScript literal type union types. The issue that I'm facing is as follows: I have instantiated a Wrapper component with a type pr ...