Although you can solve this problem with a pipe, you have to ask yourself if the re-usability of a pipe is useful to you in your particular project. Will you often need to sort objects by the "name" key on other arrays or other components in the future? Will this data be changing often enough and in ways that make it hard to simply sort in the component? Will you need the array sorted on any change to the view or inputs?
I created an edited plunker in which the array is sorted in the component's constructor, but there's no reason this functionality couldn't be moved out into its own method (sortValuesArray for instance) for re-use if necessary.
constructor() {
this.values.sort((a, b) => {
if (a.name < b.name) return -1;
else if (a.name > b.name) return 1;
else return 0;
});
}
Edited Plunker
Try this
Sort from A to end of alpahbet:
this.suppliers.sort((a,b)=>a.SupplierName.localeCompare(b.SupplierName));
Z=>A (reverse order)
this.suppliers.sort((a,b)=>b.SupplierName.localeCompare(a.SupplierName));
Your pipe expects strings but it gets objects, you should adapt it:
export class ArraySortPipe implements PipeTransform {
transform(array: Array<any>): Array<string> {
array.sort((a: any, b: any) => {
if (a.name < b.name) {
return -1;
} else if (a.name > b.name) {
return 1;
} else {
return 0;
}
});
return array;
}
}
Angular still advice not to use pipes for sorting and filtering, like in angularJs.
It will slow down your application, have some performance issues. It is a lot better to provide your sorting in your component before passing it to the template.
The reason is explained on https://angular.io/guide/pipes#no-filter-pipe
If you work with a nice structured component layout you can do it even on te setter:
@Input()
set users(users: Array<User>) {
this.usersResult = (users || []).sort((a: User, b: User) => a.name < b.name ? -1 : 1)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With