I have a array of objects and i want to sort them according to size which is a attribute of the object . Object consists of {name , size}.i want to sort the elements according to size.
service:
search(term: string): Observable<Array<Object>> {
let apiURL = `${this.apiRoot}?search=${term}`;
return this.http.get(apiURL)
.map(res => {
return res.json().results.map(items => {
return {name: items.name, population: items.population};
});
});
}
component:
ngOnInit() {
this.myshared.getSaveBtnStatus().subscribe(data => this.isSuccess = data);
this.searchField = new FormControl();
this.searchField.valueChanges
.debounceTime(400)
.distinctUntilChanged()
.switchMap(term => this.myservice.search(term))
.subscribe(value => {
this.results = value;
console.log(this.results);
}
);
HTML:
<ul class="list-group">
<li class="list-group-item" *ngFor="let items of results">
{{items.name | orderBy : ['population'] }}
</li>
</ul>
Angular 2+ doesn't have orderBy pipe. But it is very easy to build one for what you want.
Here is a simple implementation of the pipe to achieve what you want
import { Pipe, PipeTransform } from "@angular/core";
@Pipe({
name: "orderBy"
})
export class OrderByPipe implements PipeTransform {
transform(value: any[], property: any, descending?: boolean): any {
if (!value || value.length) {
return value;
}
value.sort((first: any, second: any): number => {
return first[property] > second[property] ? 1 : -1;
});
if (descending) {
return value.reverse();
}
return value;
}
}