Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 6 Sort Array of object by Date

Tags:

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",   } ] 
like image 578
Huy Le Avatar asked Aug 15 '18 22:08

Huy Le


2 Answers

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> 
like image 173
Krishna Rathore Avatar answered Oct 02 '22 08:10

Krishna Rathore


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()); 
like image 40
Pruthvi Raj Avatar answered Oct 02 '22 07:10

Pruthvi Raj