Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sort an array of strings that are dates JavaScript

I've tried using underscorejs, min and max methods but they can't handle strings. From what i've read and learnt anyway, since I get infinite back from both.

My array looks like : dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"]

How can I grab the last and the first date in these?

I tried using sort also that looks like : _.chain(dateData).sort().first().value() but I get back the last item in the array rather then the last date in the array.

like image 482
pourmesomecode Avatar asked Dec 06 '22 17:12

pourmesomecode


1 Answers

var dateData = ["26/06/2016", "04/06/2016", "13/05/2016", "20/07/2016"];

function dateToNum(d) {
  // Convert date "26/06/2016" to 20160626
  d = d.split("/"); return Number(d[2]+d[1]+d[0]);
}

dateData.sort(function(a,b){
  return dateToNum(a) - dateToNum(b);
});

console.log( dateData );

To retrieve the first, last date:

var firstDate = dateData[0];
var lastDate  = dateData[dateData.length -1];

Basically, if you first convert all your 26/06/2016 to a date Number like 20160626 you can .sort() those numbers instead.

so you're basically sorting:

20140626  
20140604  
20140513  
20140720  

resulting in:

[  
  "13/05/2016",  
  "04/06/2016",  
  "26/06/2016",  
  "20/07/2016"  
]
like image 98
Roko C. Buljan Avatar answered Dec 08 '22 07:12

Roko C. Buljan