I try to sort the array object by date for my Angular 6 application. The data has string format. I wonder if there is an existing module to perform sort in Angular or we have to build sort function it in Typescript.
Angular Template
<app-item *ngFor="let item of someArray"></app-item>
The Array
[ { CREATE_TS: "2018-08-15 17:17:30.0", Key1: "Val1", Key2: "Val2", }, { CREATE_TS: "2018-08-15 17:25:30.0", Key1: "Val1", Key2: "Val2", }, { CREATE_TS: "2018-08-15 17:28:30.0", Key1: "Val1", Key2: "Val2", } ]
You can use Array.sort
for sort data.
I have created a demo on Stackblitz. I hope this will help/guide to you/others.
component.ts
data = [ { CREATE_TS: "2018-08-15 17:17:30.0", Key1: "Val1", Key2: "Val2", }, { CREATE_TS: "2018-08-15 17:25:30.0", Key1: "Val1", Key2: "Val2", }, { CREATE_TS: "2018-08-15 17:28:30.0", Key1: "Val1", Key2: "Val2", } ] get sortData() { return this.data.sort((a, b) => { return <any>new Date(b.CREATE_TS) - <any>new Date(a.CREATE_TS); }); }
component.html
<div *ngFor="let item of sortData"> {{item.Key1}} -- {{item.CREATE_TS}} </div>
For recent first:
this.data.sort((a, b) => new Date(b.date1).getTime() - new Date(a.date1).getTime());
For OlderFirst:
this.data.sort((b, a) => new Date(b.date1).getTime() - new Date(a.date1).getTime());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With