0

hello friends I have a javascript array and I want to sort it on the date from most recent to old. The sort function isn't working I am not sure what I am doing wrong... Anyone can help me? Many thanks in advance!

[Object, Object, Object, Object, Object]
 0 : Object
 favoriteTimestamp : Object
  date : "2016-09-30 10:45:13.000000"
  timezone : "Europe/Brussels"
  timezone_type : 3

Here is my sort function:

console.log(results);

let sortedResults = results.sort(function(a, b) {
      a.favoriteTimestamp.date - b.favoriteTimestamp.date;
 });

console.log(sortedResults);

Both logs give same output so the sort isn't working :'(

Thanks for any help :)

Frank Lucas
  • 551
  • 3
  • 11
  • 25
  • Related: [Compare two dates with JavaScript](http://stackoverflow.com/questions/492994/compare-two-dates-with-javascript#493018). – Álvaro González Sep 30 '16 at 09:07
  • 1
    `(a,b) => (new Date(b.favoriteTimestamp.date)).getTime() - (new Date(a.favoriteTimestamp.date)).getTime()` – Redu Sep 30 '16 at 09:09
  • @Redu I am sorry but I don't understand your answer, is it what I have to put in the return of the sort function? – Frank Lucas Sep 30 '16 at 09:11
  • No that is the sort function's callback. In complete it is like `results.sort((a,b) => (new Date(b.favoriteTimestamp.date)).getTime() - (new Date(a.favoriteTimestamp.date)).getTime());` – Redu Sep 30 '16 at 09:12

1 Answers1

1

Sort has to return something.

results.sort(function(a, b) {
      return a.favoriteTimestamp.date - b.favoriteTimestamp.date;
});

In your case will be returned NaN, cuz you're trying to substract string from string.

Anton Chukanov
  • 645
  • 5
  • 20