Skip to content Skip to sidebar Skip to footer

How To Sort A Javascript Array By Date

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 2

Solution 1:

A simple mydate.sort() could do that.


Solution 2:

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)

Solution 3:

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);

Spread syntax not supported by older browser in that case do it like.

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);

Post a Comment for "How To Sort A Javascript Array By Date"