typescript - How to sort a list of objects using an Angular 2 Pipe -


i trying create pipe sort array of custom type.

// custom-object.ts export class customobject {     constructor(         public somestring: string,         public somenumber: number     ) {} } 

in html is:

// custom-object-form.component.ts <div class="form-group">     <label for="cricos_course_code">object: </label>     <select class="form-control" required [(ngmodel)]="model.somestring">         <option *ngfor="#object of (customobjects | sortarrayofcustomobjects)" [value]="object.somestring">{{object.somestring}}</option>     </select> </div> 

then code pipe:

// sort-custom-object.pipe.ts import {pipe, pipetransform} 'angular2/core'; import {customobject} '../custom-object';  @pipe({name: 'sortarrayofcustomobjects'}) export class sortarrayofcustomobjectspipe implements pipetransform {   transform(arr:array<customobject>): {     return arr.sort((a, b) => {       if (a.somestring > b.somestring) {         return 1;       }       if (a.somestring < b.somestring) {         return -1;       }       // must equal b       return 0;     });   } } 

now getting error in console:

exception: typeerror: cannot read property 'sort' of undefined in [(customobjects | sortarrayofcustomobjects) in formcomponent@7:24] 

based off of limited information believe want following.

@pipe({name: 'sortarrayofcustomobjects'}) export class sortarrayofcustomobjectspipe implements pipetransform {    transform(arr: customobject[], args: any): customobject[]{     return arr.sort((a, b) => {       if (a.p1 > b.p1 || a.p2 < b.p2) {         return 1;       }       if (a.p1 < b.p1 || a.p2 > b.p2) {         return -1;       }       return 0;     });   } } 

this sort objects first p1, , p2. instance.

{p1: 'aa', p2: 3}, {p1: 'cc', p2: 2}, {p1: 'bb', p2: 5}, {p1: 'bb', p2: 1}, {p1: 'aa', p2: 2}, {p1: 'dd', p2: 4} 

would sorted to

{p1: 'aa', p2: 3}, {p1: 'aa', p2: 2}, {p1: 'bb', p2: 5}, {p1: 'bb', p2: 1}, {p1: 'cc', p2: 2}, {p1: 'dd', p2: 4} 

this based on comment:

i have array of objects contain properties p1: string, p2: number etc. in form want have 2 select fields show list of p1 in alphabetical order , p2 in descending order.

usage be

*ngfor="#item of (items | sortarrayofcustomobjects)" 

update

for error receiving sure guard against undefined values in arrays using guard.

transform(arr: customobject[], args: any): customobject[]{   if(!arr){ return; }   ... } 

Comments

Popular posts from this blog

Delphi XE2 Indy10 udp client-server interchange using SendBuffer-ReceiveBuffer -

Qt ActiveX WMI QAxBase::dynamicCallHelper: ItemIndex(int): No such property in -

Enable autocomplete or intellisense in Atom editor for PHP -