Jeeten Parmar Jeeten Parmar - 3 years ago 239
Javascript Question

Filter on multiple columns using one pipe angular 2

I am trying to filter

data based on multiple columns using only one
. Right now, It filters first column value. Please check my below code and help me to sort this out.

My Code:

@Pipe({ name: "dataFilter", pure: false })
export class DataFilterPipe implements PipeTransform {
transform(value: Array<any>, filter: any[]) {
if (!filter) {
return value;
} else if (value) {
return value.filter(item => {
for (var i = 0; i < filter.length; i++) {
if (filter[i][1] == undefined) {
return true;
} else if ((typeof item[filter[i][0]] === 'string' || item[filter[i][0]] instanceof String) &&
(item[filter[i][0]].toLowerCase().indexOf(filter[i][1]) !== -1)) {
return true;
return false;

I am passing data like
dataFilter : [['column1',value1],['column2',value2],['column3',value3]]

Answer Source

Here is a solution using the object passed as multiple columns filter. I found it more convenient then passing a 2D array:

        name: 'filter'
    export class FilterPipe implements PipeTransform {
        transform(items: Array<any>, filter: {[key: string]: any }): Array<any> {
            return items.filter(item => {
                let notMatchingField = Object.keys(filter)
                                             .find(key => item[key] !== filter[key]);

                return !notMatchingField; // true if matches all fields

Having an array of objects with multiple columns:

this.people = [
  {name: 'John', age: 27, sex: 'male'},
  {name: 'Lara', age: 21, sex: 'female'},
  {name: 'Rick', age: 29, sex: 'male'},
  {name: 'Eva',  age: 27, sex: 'female'},
  {name: 'Mike', age: 27, sex: 'male'}

And a filter:

this.peopleFilter = {age: 27, sex: 'male'};

Use it like:

 <div *ngFor="let person of people | filter: peopleFilter;"></div>

As a result, two people are matching our criteria: John and Mike.

Here is the working plunker: Multiple columns filter pipe demo.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download