Reputation: 3740
So I have the following usecase where i have dates and empty strings in a table.
The problem is that the sorting doesn't do what I expected. Normally with strings it will put the empty string on the top or the bottom of the sort.
But with date it push them in between.
json = ['01-01-2018', '', '04-03-2018', '03-03-2018', '', '04-03-2018', '03-03-2018'];
this.json.sort((obj1: string, obj2: string) => {
if (new Date(obj1) > new Date(obj2)) { return 1; }
if (new Date(obj1) < new Date(obj2)) { return -1; }
return 0;
});
This will result in: 01-01-2018,,03-03-2018,04-03-2018,,03-03-2018,04-03-2018
.
Here is a simple stackblitz of it:
I have tried to make it a number a sort it. But then still the issue with the empty string stays. Does any1 have a solution how to solve this?
Upvotes: 1
Views: 62
Reputation: 62213
You need to check to see if the value is convertable to a date/time type and then return either -1 or 1 (depending on where you want them located) if they are not.
json = ['01-01-2018', '', '04-03-2018', '03-03-2018', '', '04-03-2018', '03-03-2018'];
this.json.sort((obj1: string, obj2: string) => {
if (obj1 === obj2) { return 0; } // if they are the same then no need to convert these instances to Date types later, just return 0
if (!obj1) { return 1; } // thruthy check
if (!obj2) { return -1; } // thruthy check
if (new Date(obj1) > new Date(obj2)) { return 1; }
if (new Date(obj1) < new Date(obj2)) { return -1; }
return 0;
});
// Initial array
'01-01-2018', '', '', '', '04-03-2018', '03-03-2018', '', '04-03-2018', '03-03-2018'
// Sorted array
'01-01-2018', '03-03-2018', '03-03-2018', '04-03-2018', '04-03-2018', '', '', '', ''
On a side note I recommend momentjs instead of javascript's Date
. It is much more powerful and you can include a format string with the value you are passing in so the string is parsed correctly.
Upvotes: 1
Reputation: 69440
Check if the values are set:
sort(){
this.json.sort((obj1: string, obj2: string) => {
if (!obj1 ||!obj2) {return -1}
if (new Date(obj1)> new Date(obj2)) { return 1; }
if (new Date(obj1)< new Date(obj2)) { return -1; }
return 0;
});
}
result:
,,01-01-2018,03-03-2018,03-03-2018,04-03-2018,04-03-2018
Upvotes: 0