1

Here is my array

arr=[
{
    date:'2017-06-14 14:03:49'
},
{
    date:'2017-04-20 10:25:32'
},
{
    date:'2017-06-02 15:57:16'
},
{
    date:'2017-06-02 17:52:05'
},
{
    date:'2017-06-02 21:47:13'
},
{
    date:'2017-06-14 14:01:31'
}
]

I need sort an array by date.

How can i do this,

Kindly advice me,

Thanks

ANISUNDAR
  • 787
  • 5
  • 12
  • 28
  • 1
    Dunno if that's an exact duplicate. In this case, since the date strings are ISO 8601, the compare function can be simply `return a.localCompare(b)`, so no need to covert to Date at all. – RobG Jun 16 '17 at 06:26

1 Answers1

10

Use Array#sort method and within compare function parse the string and return value corresponding by getting the difference.

var arr = [{
  date: '2017-06-14 14:03:49'
}, {
  date: '2017-04-20 10:25:32'
}, {
  date: '2017-06-02 15:57:16'
}, {
  date: '2017-06-02 17:52:05'
}, {
  date: '2017-06-02 21:47:13'
}, {
  date: '2017-06-14 14:01:31'
}];

arr.sort(function(a, b) {
  // convert date object into number to resolve issue in typescript
  return  +new Date(a.date) - +new Date(b.date);
})

console.log(arr);

Refer the issue in git: Error when doing arithmetic operations on date

Or refer : TypeScript sort by date not working

Pranav C Balan
  • 113,687
  • 23
  • 165
  • 188
  • @Pranav C Balan Thanks for ur reply.Actually i am using typescript.I am get this err left hand side an arithmetic operation must be of type any.Kindly advice me – ANISUNDAR Jun 16 '17 at 06:30
  • @ANISUNDAR : updated the answer, you need to convert it to number since it's date object.... it can be done by adding `+` before the parse date – Pranav C Balan Jun 16 '17 at 06:33
  • 1
    This also works when sorting SQL smalldatetime ie, `2018-07-05T20:24:00.000Z` – Jeff Beagley Jul 06 '18 at 15:19