I'd like to sort this JavaScript array by three values, but I can't seem to figure out how to sort by more than one property at a time.
The requirements are:
- by createdAt in descending order
- by status in descending order
- by end in ascending order
This is the array:
var items [
{ status: 3, end: 2020-06-19, createdAt: 2020-06-23T07:14:59.591Z},
{ status: 2, end: 2020-06-19, createdAt: 2020-06-21T07:14:59.591Z},
{ status: 1, end: 2020-06-01, createdAt: 2020-06-23T07:14:59.591Z},
{ status: 3, end: 2020-06-05, createdAt: 2020-06-22T07:14:59.591Z},
{ status: 3, end: 2020-06-02, createdAt: 2020-06-22T07:14:59.591Z},
];
The result should be:
var items [
{ status: 3, end: 2020-06-19, createdAt: 2020-06-23T07:14:59.591Z},
{ status: 1, end: 2020-06-01, createdAt: 2020-06-23T07:14:59.591Z},
{ status: 3, end: 2020-06-02, createdAt: 2020-06-22T07:14:59.591Z},
{ status: 3, end: 2020-06-05, createdAt: 2020-06-22T07:14:59.591Z},
{ status: 2, end: 2020-06-19, createdAt: 2020-06-21T07:14:59.591Z},
];
I tried.
test.sort((a, b) =>
new Date(b[type].createdAt) - new Date(a[type].createdAt)
|| b[type].status - a[type].status
|| Date.parse(a[type].end) - Date.parse(a[type].end));
It failed.....