Reputation: 642
I need to place all empty values at last in array. below code show what I try
1) This code sends all empty values at last in array but other values do not appear in a sorted manner.
var dateArray = [
'','',
new Date('2019-06-28',).toISOString().slice(0, 10).replace(/-/g, "."),
'',
new Date('2019-06-01').toISOString().slice(0, 10).replace(/-/g, "."),
new Date('2019-06-02').toISOString().slice(0, 10).replace(/-/g, "."),
'',''
]
dateArray.sort(function(a, b) {
return (a ==='') - (b ==='') || a - b;
});
console.log(dateArray)
2) When i remove this .toISOString().slice(0, 10).replace(/-/g, ".")
it work as expected but showing complete date in output Fri Jun 28 2019 05:30:00 GMT+0530
(India Standard Time). I only need to show this format '2019.06.28'
var dateArray = [
'','',
new Date('2019-06-28',),
'',
new Date('2019-06-01'),
new Date('2019-06-02'),
'',''
]
dateArray.sort(function(a, b) {
return (a ==='') - (b ==='') || a - b;
});
console.log(dateArray)
Upvotes: 1
Views: 67
Reputation: 4806
Try this:
const formatDate = (t)=> t.getFullYear() +"."+ (t.getMonth() + 1) + "." + (""+t.getDate()).padStart(2,'0')
var dateArray = [
'','',
formatDate(new Date('2019-06-28',)),
'',
formatDate(new Date('2019-06-01')),
formatDate(new Date('2019-06-02')),
'',''
]
dateArray.sort(function(a, b) {
return (a ==='') - (b ==='') || new Date(a) - new Date(b);
});
console.log(dateArray)
Upvotes: 1
Reputation: 82
How about this?
var dateArray = [
'','',
new Date('2019-06-28').toISOString().slice(0, 10).replace(/-/g, "."),
'',
new Date('2019-06-01').toISOString().slice(0, 10).replace(/-/g, "."),
new Date('2019-06-02').toISOString().slice(0, 10).replace(/-/g, "."),
'',''
]
dateArray.sort(function(a, b) {
return (a ==='') - (b ==='') || new Date(a) - new Date(b);
});
Upvotes: 1
Reputation: 138267
Your last version works because
new Date() - new Date()
will cast the dates to numbers (milliseconds since 1970) whereas:
'2019-06-01' - '2019-06-01'
won't work as the strings can't be converted to numbers. Therefore a - b
isn't tge right way to compare them. To compare strings, use a.localeCompare(b)
.
Upvotes: 3