Keith Keith - 1 year ago 90
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 (

) 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 = ['','']

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('');
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 -;

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


Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download