0

I am using electron, and I am trying to sort an array of objects relating to emails. I am trying to sort the array of objects based on dates, and want the option to sort either ascending or descending.

var emailObject = { file : filepath, EmailDate : parsedEmail.date, subject : parsedEmail.subject, from : parsedEmail.from, to: parsedEmail.to };
emailObjArray.push(emailObject);

I iterate through a number of emails, create the emailObject and push that it an array emailObjArray.

I tried using the following standard sort, but it has no effect.

emailObjArray.sort(function(a,b) { 
return new Date(a.EmailDate).getTime() - new Date(b.EmailDate).getTime() 
});

The EmailDate keys within the objects are as follows:-

Tue Jan 16 2018 16:40:03 GMT+0000 (Greenwich Mean Time)
Mon Nov 30 2020 16:47:28 GMT+0000 (Greenwich Mean Time)
Wed Feb 03 2021 18:18:44 GMT+0000 (Greenwich Mean Time)
Fri Jan 24 2020 12:36:17 GMT+0000 (Greenwich Mean Time)
Wed Jun 26 2019 17:53:03 GMT+0100 (British Summer Time)

When the sort is applied, the array remains in the same order.

I had reference to this answer https://stackoverflow.com/a/26759127 and tried to use this sortBy method as well, but again it had no effect.

Any clue where I am going wrong?

Resurgent
  • 425
  • 1
  • 8
  • 19
  • I've verified that the sort function you use seems to work fine for those datetime strings, sorting the array as expected. Due to this, I'd have to say your issue is from something outside of the code you show here. – Ouroborus Mar 02 '21 at 19:55
  • Ok, so this was an issue to do with promises and not being able to access the variable outside of the then function. Apologies for the problem. – Resurgent Mar 02 '21 at 20:50

1 Answers1

0

Use Date.parse() instead of new Date()

emailObjArray.sort((a, b) => {
    return Date.parse(a.EmailDate) - Date.parse(b.EmailDate);
});
Ouroborus
  • 12,316
  • 1
  • 27
  • 51
Phoenixi7
  • 1
  • 1