1

How can I sort Dates like below in a NeDb Database with a JavaScript function?

This sort command in the function loaddata() does not work:

loaddata() {
  this.$db.DBData.find({}).sort({ pubDate: 1 }).exec((err, docs) => {
    this.Data = docs;
  });
}

Examples for pubDate:

Fri, 29 Jun 2018 20:15:00 +0200
Mon, 25 Jun 2018 04:22:00 +0200
Fri, 29 Jun 2018 05:10:00 +0200
Sat, 30 Jun 2018 23:35:43 +0200

Thanks in advance!

lannenere
  • 69
  • 1
  • 2
  • 5

2 Answers2

0

If the dates are being stored as strings then sorting them as strings is going to be alphabetizing them by the short day. If you convert them to Date objects before sorting it should work:

loaddata() {
  this.$db.DBData.find({}).exec((err, docs) => {
    let newDocs = docs.map((doc)=>{
      doc.pubDate = new Date(doc.puDate).valueOf();
    });
    newDocs.sort((a, b)=>{
      return a.pubDate - b.pubDate; //you may have to switch the order
    });
    this.Data = newDocs;
  });
}

Another solution would be to save the Date value instead of the string representation. For example the dates you gave above translate to:

[1530296100000, 1529893320000, 1530241800000, 1530394543000] 

Then sorting them results in:

[1529893320000, 1530241800000, 1530296100000, 1530394543000]

Converted back that's:

["Sun Jun 24 2018 22:22:00 GMT-0400 (Eastern Daylight Time)", 
"Thu Jun 28 2018 23:10:00 GMT-0400 (Eastern Daylight Time)", 
"Fri Jun 29 2018 14:15:00 GMT-0400 (Eastern Daylight Time)", 
"Sat Jun 30 2018 17:35:43 GMT-0400 (Eastern Daylight Time)"]

You can see how they are sorted in order now and back in their string representation. Sorry for the time zone conversion I ran this example in the console on my browser to make sure it works.

0

Harry Chilinguerian's answer is on the right track, but remember to return the document inside the map function. For my solution, I decided to keep the original date and instead create a different property to store the date value. Finally, I think most users would prefer reverse chronological ordering:

loaddata() {
  this.$db.DBData.find({}).exec((err, docs) => {
    let newDocs = docs.map((doc)=>{
      doc.pubDateValue = new Date(doc.pubDate).valueOf(); // new property
      return doc; // return the new document
    });
    newDocs.sort((a, b)=>{
      return b.pubDateValue - a.pubDateValue; // reverse chronological order
    });
    this.Data = newDocs;
  });
}
ThaddeusM
  • 3
  • 2