AyDee
AyDee

Reputation: 221

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
2016,09,09
2016,09,13
2016,10,01
2016,10,02

Upvotes: 3

Views: 9942

Answers (4)

Habibi 27
Habibi 27

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

Pranav C Balan
Pranav C Balan

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

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

Upvotes: 1

Rajesh
Rajesh

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

Hassan
Hassan

Reputation: 930

A simple mydate.sort() could do that.

Upvotes: 8

Related Questions