applying multiple angular filters on table column values

I'm currently facing a challenge with implementing a filter pipe that can handle multiple values across multiple attributes in a table.

While I have successfully managed to filter multiple values on a single attribute, I am struggling to achieve the same for multiple values across multiple attributes.

Below is an excerpt from my existing pipe filter implementation which caters to filtering multiple values within a single attribute:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'vFilter',
  pure: false
})

export class VFilterPipe implements PipeTransform {

  transform(vList: any[], vfilter?: any): any {
    if (!vList || !Object.keys(vfilter).length) {
      return vList;
    } 
    return vList.filter(item => {
          for (let key in vfilter) {
            for(let value in vfilter[key]){
             if ((item[key] === undefined || item[key] == vfilter[key][value])) 
             {
              return true;
             }
           }
           return false;
         }
         return false;
       });
  }
}

Here is the input array provided:

vList = [{'name':'jack','age':'25'},{'name':'sam','age':'25'},{'name':'smith','age':'25'},{'name':'jack','age':'28'}]

vfilter = {'name':['jack','sam'],'age':['25']}

The expected filtered output should be as follows:

vList = [{'name':'jack','age':'25'},{'name':'sam','age':'25'}]

However, the actual result obtained is:

vList = [{'name':'jack','age':'25'},{'name':'sam','age':'25'},{'name':'jack','age':'28'}]

If you have any suggestions or solutions to this logical issue, your help would be greatly appreciated.

Answer №1

Your code currently has a logic bug where it returns `true` if any of the filters match, but you actually want it to return `true` only if all the filters match.

Check out the edited code on StackBlitz here.

function applyFilters(list: any[], filter?: any): any {
  if (!list || !Object.keys(filter).length) {
    return list;
  } 
  return list.filter(item => {
          return Object.keys(filter)
            .filter(key => filter.hasOwnProperty(key))
            .every(key => {
              if(!item[key]) return true; // matches undefined value
              const values = filter[key] as any[];
              return values.some(value => value === item[key]);
          });
      });
}

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

Guide to defining font style in vanilla-extract/CSS

I'm trying to import a fontFace using vanilla-extract/css but I'm having trouble figuring out how to do it. The code provided in the documentation is as follows: import { fontFace, style } from '@vanilla-extract/css'; const myFont = fo ...

Using the parameter of type 'never' is necessary as per the TypeScript error message, which states that the argument of type 'string' cannot be assigned to it. This error persists even when

https://i.sstatic.net/tkX07.png const index = selectedActivities.value.indexOf(activity_id); I encountered a TypeScript error saying 'Argument of type 'string' is not assignable to parameter of type 'never'. How can I fix this iss ...

What is the best way to transfer information from a child Angular app to a parent non-Angular app

If I have a plain JavaScript parent application with a child Angular application, how can I notify the parent application of any data changes in the child Angular application? The child application is loaded in a div, not in an iframe. ...

Issues with loading SourceMap in DevTools after upgrading from Bootstrap 3 to 4

I am currently working on a project with Angular 6 and .NET MVC where I am in the process of upgrading from Bootstrap 3 to Bootstrap 4. Initially, I had been using the Bootstrap 3 CDN and everything was working smoothly. However, I recently had to switch t ...

Is it possible to utilize a variable for binding, incorporate it in a condition, and then return the variable, all while

There are times when I bind a variable, use it to check a condition, and then return it based on the result. const val = getAttribute(svgEl, "fill"); if (val) { return convertColorToTgml(val); } const ancestorVal = svgAncestorValue(svgEl, "fill"); if (a ...

Retrieving PHP information in an ionic 3 user interface

We are experiencing a problem with displaying data in Ionic 3, as the data is being sourced from PHP REST. Here is my Angular code for retrieving the data: this.auth.displayinformation(this.customer_info.cid).subscribe(takecusinfo => { if(takecusi ...

Having trouble with Angular NgbModal beforeDismiss feature?

My goal is to add a class to the pop up modal before closing it, and then have it wait for a brief period before actually closing. I've been trying to do this using the beforeDismiss feature in the NgbModalOptions options in Angular Bootstrap's d ...

Angular2 with Webpack causes duplication of styles in the header

I'm currently working on integrating Angular2 with universal + webpack, but I have encountered an issue where styles are being loaded twice in the head element. I haven't made any changes to the git repo that I forked from. You can find it here: ...

Apollo GraphQL Server is unable to provide data to Angular

I've been facing a challenge for quite some time now trying to make my Angular component communicate with an Apollo GraphQL server using a simple Query (PingGQLService). I'm currently utilizing apollo-angular 4.1.0 and @apollo/client 3.0.0, and h ...

Repeatedly copying data from one row to another in TypeScript

Within my React TypeScript component, I am working with an array of objects. Each row in the array contains a repeat button, and I am looking to create a function that will copy the data from the current row and paste it into all remaining rows. https://i. ...

Is there a way for me to extract information from a static HTML page, like the meta tag, in a simple manner

In my Angular 2 application, I am using Flask (Python framework) to serve up the static HTML content when accessed through the index. My goal is to show the version of the application on the AboutComponent. Currently, I have Flask injecting the version int ...

An error has occurred with mocha and ts-node unable to locate the local .d.ts file

This is the structure of my project: |_typetests | |_type.test.ts | | myproj.d.ts tsconfig.json Here is how my tsconfig.json file is configured: { "compilerOptions": { "module": "commonjs", "moduleResolution": "node", "lib": ...

Is it possible for a TypeScript interface to inherit from a Function?

While studying Angular, I found this intriguing declaration: interface IMessagesOperation extends Function { (messages: Message[]): Message[]; } I'm curious about what this means, especially why Function is capitalized as F instead of being lowercase ...

Troubleshooting Angular 2 routing: when routerLink is empty, it fails to function

As I configure my routing, I encountered a problem. At the moment, these are my 2 routes: const appRoutes: Routes = [ { path: '', component: HomeComponent }, { path: 'products', component: ProductComponent} ]; Is it not allow ...

What is the process for incorporating a custom type into Next.js's NextApiRequest object?

I have implemented a middleware to verify JWT tokens for API requests in Next.js. The middleware is written in TypeScript, but I encountered a type error. Below is my code snippet: import { verifyJwtToken } from "../utils/verifyJwtToken.js"; imp ...

How does a brand new installation of VSCode believe it comes pre-equipped with TypeScript capabilities?

Operating on Windows 10 Enterprise, After investing several hours and experimenting on various VMs, Interesting Observation #1 Upon opening a .ts file in vscode, it appears to be recognized as TypeScript 2.3.4 as per the screenshot provided below: http ...

Utilizing Angular 2's offline capabilities for loading locally stored JSON files in a project folder

I've been attempting to load a local JSON file from my Angular 2 project folder using the HTTP GET method. Here is an example of the code snippet: private _productURL = 'api/products/products.json'; getProducts(): Observable<any> ...

ngx-graphs -> ngx-graphs-bar-vertical x-axis labels with multiple lines

I'm using 'ngx-charts' with Angular, and I have encountered an issue with long text on my X axis labels. The text overflows and displays three dots instead of wrapping onto multiple lines. Is there a way to make the text wrap onto multiple l ...

Missing expected property in TypeScript casting operation

I recently came across this intriguing playground example outlining a scenario where I attempted to convert an object literal into an object with specific properties, but encountered unexpected results. class X { y: string; get hi(): string { ...

Exploring SVG Graphics, Images, and Icons with Nativescript-vue

Can images and icons in SVG format be used, and if so, how can they be implemented? I am currently utilizing NativeScript-Vue 6.0 with TypeScript. ...