I am having problems sorting an array of an object in Angular2.
The object looks like this:
[ { "name": "t10", "ts": 1476778297100, "value": "32.339264", "xid": "DP_049908" }, { "name": "t17", "ts": 1476778341100, "value": "true", "xid": "DP_693259" }, { "name": "t16", "ts": 1476778341100, "value": "true", "xid": "DP_891890" } ]
And stored inside the values variable.
All I want to do is do a *ngFor sort it by the name property.
<table *ngIf="values.length"> <tr *ngFor="let elem of values"> <td>{{ elem.name }}</td> <td>{{ elem.ts }}</td> <td>{{ elem.value }}</td> </tr> </table>
I tried to do this with pipes, but failed unsuccessfully. Any help was appreciated.
Link to the plunker : https://plnkr.co/edit/e9laTBnqJKb8VzhHEBmn?p=preview
Edit
My pipe:
import {Component, Inject, OnInit, Pipe, PipeTransform} from '@angular/core'; @Component({ selector: 'watchlist', templateUrl: './watchlist.component.html', styleUrls: ['./watchlist.component.css'], pipes: [ ArraySortPipe ] }) @Pipe({ name: "sort" }) export class ArraySortPipe implements PipeTransform { 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 just put the pipe name in the html file:
<tr *ngFor="let elem of values | sort">
javascript sorting arrays angular typescript
user7209780
source share