Reputation: 221
For example in my array i have this data
var mydate = [
"2016,10,01",
"2016,09,13",
"2016,09,05",
"2016,09,09",
"2016,10,02"];
How to sort this? I want this output:
2016,09,05
2016,09,09
2016,09,13
2016,10,01
2016,10,02
Upvotes: 3
Views: 9942
Reputation: 61
var mydate = [
"2016,10,01",
"2016,09,13",
"2016,09,05",
"2016,09,09",
"2016,10,02"
];
mydate.sort(function(a,b){
var da = new Date(a).getTime();
var db = new Date(b).getTime();
return da - db
});
console.log(mydate)
Upvotes: 0
Reputation: 115272
Use Array#sort
method with Date
constructor.
var mydate = [
"2016,10,01",
"2016,09,13",
"2016,09,05",
"2016,09,09",
"2016,10,02"
];
mydate.sort(function(a, b) {
return new Date(...a.split(',')) - new Date(...b.split(','));
});
console.log(mydate);
var mydate = [
"2016,10,01",
"2016,09,13",
"2016,09,05",
"2016,09,09",
"2016,10,02"
];
mydate.sort(function(a, b) {
var a1 = a.split(','),
b1 = b.split(',');
return new Date(a1[0], a1[1], a1[2]) - new Date(b1[0], b1[1], b1[2]);
});
console.log(mydate);
Upvotes: 1
Reputation: 24955
You will have to parse date into date object and then sort using date.getTime()
var mydate = [
"2016,10,01",
"2016,09,13",
"2016,09,05",
"2016,09,09",
"2016,10,02"
];
mydate.sort(function(a,b){
var da = new Date(a).getTime();
var db = new Date(b).getTime();
return da < db ? -1 : da > db ? 1 : 0
});
console.log(mydate)
Upvotes: 2