-1

I have a JavaScript array below.

 const arr = [
     "2016-10-10 12:03:05",
     "2016-10-10 12:03:05",
     "2016-10-10 2:30:01",
     "2016-10-10 2:30:01",
     "2016-10-10 2:00:06",
     "2016-10-10 2:00:06",
     "2016-10-10 2:00:06",
     "2016-10-10 1:04:01",
     "2016-10-10 1:04:01"
 ];

which i want to sort in descending order or the latest date first.

I was expecting the code below to sort my data for me

 console.log('the real sort is', arr.sort((a,b) => moment(b).diff(moment(a))));

However, the above print

[ 
  "2016-10-10 12:03:05", 
  "2016-10-10 12:03:05", 
  "2016-10-10 2:30:01", 
  "2016-10-10 2:30:01", 
  "2016-10-10 2:00:06", 
  "2016-10-10 2:00:06", 
  "2016-10-10 2:00:06", 
  "2016-10-10 1:04:01", 
  "2016-10-10 1:04:01"
]

and console.log('the real sort is', arr.sort((a,b) => moment(a).diff(moment(b))));

returns

[
 "2016-10-10 1:04:01",
 "2016-10-10 1:04:01",
 "2016-10-10 2:00:06",
 "2016-10-10 2:00:06",
 "2016-10-10 2:00:06",
 "2016-10-10 2:30:01",
 "2016-10-10 2:30:01",
 "2016-10-10 12:03:05",
 "2016-10-10 12:03:05"
]

It seems to me like it only reverse the indexes . Please how do i sort this kind of array accordingly ? Any help would be appreciated

Update

Very sorry for wasting your time. I naively forgot , mistook and expect the time to be in 12 Hr format hence was expecting the pm time to be later than am time. Not only was i wrong but it turns out that we have a an angular pipe that converts the display to the 12 hr equivalent and in local time. So my conversion should be fine, unfortunately it took me many hours to realised that . I apologized once again.

Nuru Salihu
  • 4,756
  • 17
  • 65
  • 116

1 Answers1

2

You can easily do this without moment like this:

arr.sort((a, b) => new Date(a) - new Date(b));

When you subtract 2 date objects, their valueOf() method will be called, which returns the timestamp corresponding to that date.

Mouad Debbar
  • 3,126
  • 2
  • 20
  • 20
  • I tried `new Date(a).getTime() - new Date(b).getTime()`. get thesame result. – Nuru Salihu Nov 30 '16 at 02:12
  • The above code prints as I would expect: `["2016-10-10 1:04:01", "2016-10-10 1:04:01", "2016-10-10 2:00:06", "2016-10-10 2:00:06", "2016-10-10 2:00:06", "2016-10-10 2:30:01", "2016-10-10 2:30:01", "2016-10-10 12:03:05", "2016-10-10 12:03:05"]` https://jsfiddle.net/bo8bjaan/ – Evan Trimboli Nov 30 '16 at 02:16
  • @EvanTrimboli Sorry just realized its in 24 hrs format. Totally misunderstood. – Nuru Salihu Nov 30 '16 at 02:19