Here is a solution using the object passed as multiple columns filter. I found it more convenient then passing a 2D array:
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(items: Array<any>, filter: {[key: string]: any }): Array<any> {
return items.filter(item => {
const 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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…