i have an array in javascript that looks like this
Array[9]
0: "01/06/2016"
1: "02/06/2016"
2: "23/05/2016"
3: "24/05/2016"
4: "25/05/2016"
5: "26/05/2016"
6: "27/05/2016"
7: "28/05/2016"
8: "31/05/2016"
length: 9__proto__: Array[0]
i want to order them so the oldest date is first and the most recent is last. i have tried
days.sort(function(a,b) {
return new Date(a).getTime() - new Date(b).getTime()
});
but i guess because of the format of the date? this doesn't work. what else could i try?
expected output
Array[9]
0: "23/05/2016"
1: "24/05/2016"
2: "25/05/2016"
3: "26/05/2016"
4: "27/05/2016"
5: "28/05/2016"
6: "31/05/2016"
7: "01/06/2016"
8: "02/06/2016"
length: 9__proto__: Array[0]
You can slit the string to year, month, date and use that to create the date for comparing.
new Date("01/06/2016") is wont be parsed as you think. The result actually is Jan 06 2016.
days = ["01/06/2016", "02/06/2016", "23/05/2016", "24/05/2016", "25/05/2016", "26/05/2016", "27/05/2016", "28/05/2016", "31/05/2016"];
days.sort(function(a, b) {
aArr = a.split('/');
bArr = b.split('/');
return new Date(aArr[2], Number(aArr[1])-1, aArr[0]).getTime() - new Date(bArr[2], Number(bArr[1])-1, bArr[0]).getTime()
});
console.log(days);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With