I have problems with sorting an array of object in Angular2.
The object looks like:
[
{
"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 is being stored inside the values variable.
All I want is to make the *ngFor loop 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>
Tried to do it with pipes, but failed miserably. Any help appreciated.
Plunker link: 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 into html file:
<tr *ngFor="let elem of values | sort">