How filter array with different parameters using pipes

How filter array with different parameters using pipes

angular 4 filter array multiple values
angular pipe multiple arguments
angular filter multiple parameters
angular filter by multiple properties
filter pipe in angular 8
angular 7 search filter
pass multiple arguments in pipe
angular multiple pipes

My JSON file called employee looks like this:

[
    {
        "id": "E01",
        "name": "neetha",
        "age": 20,
        "gender": "female",
    },
    {
        "id": "E02",
        "name": "Kiran",
        "age": 24,
        "gender": "male",
    },
   {
        "id": "E03",
        "name": "Jhon",
        "age": 28,
        "gender": "male",
    }   
]

I have an component called list where i am filtering this employees with their names using custom pipes like this:

list.component.html

<div>
    <mat-form-field>
        <input matInput [(ngModel)]="searchTerm"  placeholder="Search">
    </mat-form-field>
    <mat-selection-list class="list">
        <mat-list-option   *ngFor="let employee of employees | employeeFilter : searchTerm; let i=index">
            <a mat-list-item (click)="onSelect(employee,i)"><span>{{employee.name}}</span></a>
        </mat-list-option>
    </mat-selection-list>
</div>

employee-filter.pipe.ts

import { PipeTransform, Pipe } from '@angular/core';
import { Employee } from '../models/employee.model';

@Pipe({
    name: 'employeeFilter'
})
export class EmployeeFilterPipe implements PipeTransform {
    transform(employees: Employee[], searchTerm: string): Employee[] {
        if (!employees || !searchTerm) {
            return employees;
        }

        return employees.filter(employee =>
            employee.name.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1);
    }
}

Now the i am filtering using the name property, but i want to filter using age,gender along with name. Using the same input field i want to filter. How can i achieve this?


Just use or operator ||

return employees.filter(employee =>
            employee.name.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1)
|| employee.age.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1)
|| employee.gender.toLowerCase().indexOf(searchTerm.toLowerCase()) !== -1)
); 

How filter array with different parameters using pipes, You can see that the first argument to the filter pipe is an object with keys set to whatever the user typed into the filter textbox. Notice I use it to distinguish whether the filter pipe will match all of the items if (filter && Array. In your component's template you can use multiple arguments by separating them with colons: {{ myData | myPipe: 'arg1':'arg2':'arg3' }} From your code it will look like this: new MyPipe().transform(myData, arg1, arg2, arg3) And in your transform function inside your pipe you can use the arguments like this:


 transform(employees: any[], searchTerm: string): any[] {

    if (!employees || !searchTerm) {
        return employees;
    }

    // remove the "id"
    const { id, ...objWithoutID } = employee;
    let values = Object.keys(objWithoutID).map(key => employee[key]);          
    // If you want fast and have a very large array of words, call toLowerCase once-  
    return values.join('|').toLowerCase().split('|').toString().indexOf(searchTerm.toString())!==-1
    })
}

Working Stackblitz

Angular Pipes Filtering on Multiple Keys – Longing to know, In earlier blog posts we had seen simplistic scenario of using pipes, but what if transform method, for passing multiple filter parameters to the pipe in the transform(items: Array, nameSearch: string, emailSearch: string,  Back in part 8 – Call O365 Roadmap Web Service Weekly Digest you will see there is a Filter Array that I left alone at that time. This is because the scope of the blog post was to get a weekly digest of posts made by the Microsoft 365 Roadmap. The expression within the Filter Array get's you the last 7 days of updates and does no more.


In this case, you need to filter the employee in the pipe as follows:

return employees.filter((employee) => Object.values(employee).includes(searchTerm));

And your code will look like something:

import { PipeTransform, Pipe } from '@angular/core';
import { Employee } from '../models/employee.model';

@Pipe({
    name: 'employeeFilter'
})
export class EmployeeFilterPipe implements PipeTransform {
    transform(employees: Employee[], searchTerm: string): Employee[] {
        if (!employees || !searchTerm) {
            return employees;
        }

   //Parse a string to integer for the age
    let searchValue;
   if (!Number.isNaN(Number(searchTerm))) {
      searchValue = parseInt(searchTerm);
    } else {
      searchValue = searchTerm;
    }

        return employees.filter((employee) => (Object as any).values(employee).includes(searchValue));
    }
}

To see this filter working see this: javascript filter array of objects

Angular 2 – Pipes passing multiple filters to Pipes , is called for every change detection cycle no matter whether the value or parameter(s) changes. The filter pipe has to be modified accordingly. It access the “isAnd” parameter along with the original filter data. It uses the “isAnd” to toggle between two different matching routines. When “isAnd” is true, the filtering is the same as before.


Creating a pipe for a single output is not really cool. You can use it like that on the component:

get filteredEmployees() {

return employees.filter( anything you want )

}

In html just call use {{ filteredEmployees }}.

If such filtering is at least a bit complex and common for multiple components, create a service for storing such functions and call it in the getter above

What is impure pipe in Angular?, If the pipe accepts multiple parameters, separate the values with colons. For example, {{ slice:1:5 }} creates a new array or string containing a subset of the elements To demonstrate this issue, change the previous example to filter the list of  You can easily pass multiple arguments in pipe in angular 6, angular 7, angular 8 and angular 9 application. In this example we will create 'descPipe' custom pipe and create dynamic description with multiple parameters. basically we will create "persons" array and print in table then using custom pipe that will create dynamic description.


Pipes, I have an component called list where i am filtering this employees with their names using custom pipes like this: list.component.html The filter () method creates a new array with all the elements that pass the test implemented by the callback () function. Internally, the filter () method iterates over each element of the array and pass each element to the callback function. If the callback function returns true, it includes the element in the return array.


Transforming Data Using Pipes, Custom Pipes in Angular; Using Custom Pipes; Creating a Custom Pipe; Pipe and PipeTransform; Pipe Transform Value; Pipes with Arguments FREE eBook: ForEach, Map, Filter, Reduce, Some, Every, Find and tricks - it covers all you need Todd Motto, author of Exploring JavaScript Array Methods. If a thisArg parameter is provided to filter, it will be used as the callback's this value. Otherwise, the value undefined will be used as its this value. The this value ultimately observable by callback is determined according to the usual rules for determining the this seen by a function. filter() does not mutate the array on which it is called.


How filter array with different parameters using pipes – Onooks, I got part of this custom pipe from stack overflow and added in the forEach loops We could also create a more generic filter using an object array: items: any[]. An array is a special type of data type that stores multiple values of different data​  This will be the Simplest way to filter an array with respect to another array. Both arrays can have objects inside them instead of values. let array1 = [1,3,47,1,6,7]; let array2 = [3,6]; let filteredArray1 = array1.filter(el => array2.includes(el));