0

I am trying to sort my array of objects which have date values by date newest first and newest last.

I have the following code:

function comp(a, b) {
  return new Date(a.jsDate) - new Date(b.jsDate);
}

function compNewestFirst(a, b) {
  return new Date(b.jsDate) - new Date(a.jsDate);
}

Please note JS Date is a valid date/format the new Date() accepts.

I can getting it ordering oldest first but not newest first and I have tried the following:

return new Date(b.jsDate) + new Date(a.jsDate);

Current I CANNOT sort by newest date first and it only works OLDEST first.

Thanks

Lemex
  • 3,646
  • 14
  • 47
  • 82

1 Answers1

1

Try it:

function compNewestFirst(a, b) {
  return new Date(b.jsDate).getTime() - new Date(a.jsDate).getTime();
}

The return will be a negative integer and you will be able to order.

Here is a FIDDLE;

nanndoj
  • 5,650
  • 6
  • 26
  • 39