I'm using Typescript and Angular2. I have a pipe that filters a list of results. Now, I want to sort that list in alphabetical etc. How would I do this?
Asked
Active
Viewed 2,757 times
0
-
Check here: http://stackoverflow.com/questions/35176188/angular2-sorting-pipe-with-object-array – Feb 03 '16 at 14:34
1 Answers
5
You could implement a custom pipe for this that leverages the sort
method of arrays:
import { Pipe } from "angular2/core";
@Pipe({
name: "sort"
})
export class ArraySortPipe {
transform(array: Array<string>, args: string): Array<string> {
array.sort((a: any, b: any) => {
if (a < b) {
return -1;
} else if (a > b) {
return 1;
} else {
return 0;
}
});
return array;
}
}
And use then this pipe by leveraging pipe chaining:
<li *ngFor="list | filter | sort"> (...) </li>
It's a simple sample for arrays with string values but you can have some advanced sorting processing (based on object attributes in the case of object array, based on sorting parameters, ...).
Here is a plunkr for this: https://plnkr.co/edit/WbzqDDOqN1oAhvqMkQRQ?p=preview.
Hope it helps you, Thierry

Thierry Templier
- 198,364
- 44
- 396
- 360
-
-
-
I updated my answer for alphabetical order and provided a plunkr... – Thierry Templier Jan 27 '16 at 12:18