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
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
A simple mydate.sort() could do that.
.sort() not sort based on string values?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)
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);