Angular 6 Sort Array of object by Date
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>
you can use the sort
function for arrays, it takes in compare function. Parse the Date string into a date object and sort by it.
read more about here
var myArr = [
{
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",
}
]
myArr.sort((val)=> {return new Date(val.CREATE_TS)})
Ascending
myArr.sort((val1, val2)=> {return new Date(val1.CREATE_TS) - new
Date(val2.CREATE_TS)})
Descending
myArr.sort((val1, val2)=> {return new Date(val2.CREATE_TS) - new
Date(val1.CREATE_TS)})
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());