Keith Keith - 4 months ago 15
Javascript Question

Sorting an array in javascript based on date

I'm trying to parse multiple subreddit feeds in a Google Script. I can call this Google Script (

redditFeeds()
) and it returns the title, link, and date to my spreadsheet. However, I want to sort the posts by date so I can see the most recent posts first. I've tried using sort() on the array in various ways and can't get anything sort by descending date. I've even tried converting the date to a Date object and that didn't fix it.

function redditFeeds() {

var entries_array = [];
var subreddit_array = ['https://www.reddit.com/r/funny/top/.rss','https://www.reddit.com/r/news/top/.rss']

for (var s = 0; s < subreddit_array.length; s++) {

var xml = UrlFetchApp.fetch(subreddit_array[s]).getContentText();
var document = XmlService.parse(xml);
var root = document.getRootElement();
var atom = XmlService.getNamespace('http://www.w3.org/2005/Atom');
var entries = document.getRootElement().getChildren('entry', atom);

for (var i = 0; i < entries.length; i++) {
var title = entries[i].getChild('title', atom).getText();
var title = entries[i].getChild('link', atom).getText();
var link = entries[i].getChild('link', atom).getAttribute('href').getValue();
var date = entries[i].getChild('updated', atom).getValue();
entries_array.push([title, link, date]);
}
}

//return entries_array;

//doesn't work
//entries_array.sort(function(a,b) {
// return a.date - b.date;
//});

//also not working
return entries_array.sort(function(a,b) {
new Date(a.date).getTime() - new Date(b.date).getTime();
});

}

Answer

I think you want the below, assuming entries_array looks like I think it does. I have no idea what start was supposed to be in your code... I think each entry in entries_array is an array with three members in it, the third being some sort of representation of a date. If it's one that can be parsed by new Date, then this code should work:

return entries_array.sort(function (a, b) { 
  return new Date(a[2]) - new Date(b[2]);
});

If that's not right, please share what entries_array looks like.

Comments