To filter Json data in alphabetical order in angular 6
I took bajaran's answer and modified it to not fail when the content of a field is null
and to work case insensitively:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'sort'
})
export class SortPipe implements PipeTransform {
transform(array: any, field: string): any[] {
if (!array) {
return array;
}
array.sort((a: any, b: any) => {
if ((a[field] || '').toLowerCase() < (b[field] || '').toLowerCase()) {
return -1;
} else if ((a[field] || '').toLowerCase() > (b[field] || '').toLowerCase()) {
return 1;
} else {
return 0;
}
});
return array;
}
}
To Display in any alphabetical order make the custom pipe
import { Pipe, PipeTransform } from "@angular/core";
@Pipe({
name: "sort"
})
export class ArraySortPipe implements PipeTransform {
transform(array: any[], field: string): any[] {
array.sort((a: any, b: any) => {
if (a[field] < b[field]) {
return -1;
} else if (a[field] > b[field]) {
return 1;
} else {
return 0;
}
});
return array;
}
}
and used that like
<mat-card class="example-card" *ngFor="let filteredScreen of
filteredScreens | sort : fieldName" ; let i = index">
For searching the last name split that field and pass to custom search function or you can also create the pipe for same
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
name: 'filter'
})
export class FilterPipe implements PipeTransform {
transform(items: any[], searchText: string): any[] {
if(!items) return [];
if(!searchText) return items;
searchText = searchText.toLowerCase();
return items.filter( it => {
return it.toLowerCase().includes(searchText);
});
}
}
Refer to below link for search functionality
Serach pipe