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

4
  • Related: Compare two dates with JavaScript. Commented Sep 30, 2016 at 9:07
  • 1
    (a,b) => (new Date(b.favoriteTimestamp.date)).getTime() - (new Date(a.favoriteTimestamp.date)).getTime() Commented Sep 30, 2016 at 9: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? Commented Sep 30, 2016 at 9: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()); Commented Sep 30, 2016 at 9:12

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

the original callback returns something ... always undefined.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.