I'm trying to refactor some really bonkers and overcomplicated code that tries to do some sorting on an array of objects. The array looks like this:
[
{
"status": "CANCELLED",
"createdDate": "2020-02-19T22:22:43Z",
"dueDate": "2020-02-20T06:00:00Z"
},
{
"status": "OPEN",
"createdDate": "2020-01-16T22:01:35Z"
},
{
"status": "OPEN",
"createdDate": "2020-02-19T22:24:28Z"
},
{
"status": "OPEN",
"createdDate": "2020-01-27T23:30:08Z"
},
{
"status": "COMPLETE",
"createdDate": "2019-08-27T04:53:46Z"
},
{
"status": "OPEN",
"createdDate": "2020-01-15T08:39:24Z",
"dueDate": "2020-01-16T08:38:00Z"
},
{
"status": "OPEN",
"createdDate": "2020-01-16T22:02:43Z"
},
{
"status": "OPEN",
"createdDate": "2020-01-16T04:48:56Z"
},
{
"status": "OPEN",
"createdDate": "2020-03-31T04:07:17Z"
},
{
"status": "OPEN",
"createdDate": "2020-01-27T23:27:25Z"
},
{
"status": "OPEN",
"createdDate": "2020-03-12T03:28:24Z"
},
{
"status": "COMPLETE",
"createdDate": "2019-04-22T23:08:29Z",
"dueDate": "2019-04-23T07:00:00Z"
},
{
"status": "OPEN",
"createdDate": "2020-01-16T21:49:11Z",
"dueDate": "2020-01-17T06:00:00Z"
},
{
"status": "CANCELLED",
"createdDate": "2019-04-22T23:13:22Z",
"dueDate": "2019-04-23T07:00:00Z"
},
{
"status": "OPEN",
"createdDate": "2020-01-21T23:36:43Z"
},
{
"status": "OPEN",
"createdDate": "2020-01-06T02:51:48Z"
},
{
"status": "OPEN",
"createdDate": "2020-01-16T03:46:44Z"
},
{
"status": "OPEN",
"createdDate": "2020-01-16T03:46:11Z"
},
{
"status": "OPEN",
"createdDate": "2020-01-28T02:42:15Z"
}
]
The conditions are as follows in order of priority:
- The items that have a due date and a status of 'OPEN' come at the top and should be in ascending order of dueDate.
- They should respect the following order of 'status': 'OPEN', 'COMPLETED', 'CANCELLED'
- They should be ordered by 'createdDate' descending, so most recent items come at the top
I've been playing around with the Array.prototype.sort function learning how it works but at points not really knowing what I was doing. I was able however to meet the first and second conditions but not the third one.
The working code I have is:
this.items = this.items.sort((a, b) => {
let rv = 0;
if (b.status === 'OPEN' || a.status === 'CANCELLED') {
rv = 1;
}
if (a.dueDate && a.status === 'OPEN') {
rv = -1;
}
return rv;
});
But when I try to fit the third condition the other conditions are no longer respected. It would look something like:
if(new Date(a.createdDate).getTime() < new Date(b.createdDate).getTime()) {
// return something
}
I'm thinking it may not be possible inside the same sort function and will have to split it into several, or maybe I need someone a lot wittier than I am.
Your help is appreciated