Skip to content

Instantly share code, notes, and snippets.

@AngelAlexQC
Created May 24, 2022 13:26
Show Gist options
  • Save AngelAlexQC/838999de2dc42bf0971f07ae6293799a to your computer and use it in GitHub Desktop.
Save AngelAlexQC/838999de2dc42bf0971f07ae6293799a to your computer and use it in GitHub Desktop.
Angular Filter pipe
import { Pipe, PipeTransform, Injectable } from '@angular/core';
@Pipe({
name: 'filter'
})
@Injectable()
export class FilterPipe implements PipeTransform {
transform(items: any, filter: any, defaultFilter: boolean = true): any {
if (!filter) {
return items;
}
if (!Array.isArray(items)) {
return items;
}
if (filter && Array.isArray(items)) {
const filterKeys = Object.keys(filter);
if (defaultFilter) {
return items.filter(item =>
filterKeys.reduce((x, keyName) =>
(x && new RegExp(filter[keyName], 'gi').test(item[keyName])) || filter[keyName] === '', true));
} else {
return items.filter(item => {
return filterKeys.some((keyName) => {
return new RegExp(filter[keyName], 'gi').test(item[keyName]) || filter[keyName] === '';
});
});
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment