2

I have an array containing many objects that each have a date property in the following format: { date: 'December 2017' }. I want to sort all of them in descending order. How can I achieve this?

I've tried using a secondary object tying each of the month names to its corresponding number and then converting each into a new Date to sort. I'm successfully converting each of the objects into the new Date format but I'm unsure how to then use this to sort my original array.

let dates = [{ date: 'December 2016' }, { date: 'December 2017' }, { date: 'November 2016' }, { date: 'August 2015' }, { date: 'June 2018' }, { date: 'May 2017' }];
let months = { "January": 1, "February": 2, "March": 3, "April": 4, "May": 5, "June": 6, "July": 7, "August": 8, "September": 9, "October": 10, "November": 11, "December": 12 };
let newDates = [];

for (var i = 0; i < dates.length; i++) {
  newDates.push(new Date(dates[i].date.replace(' ', ', ')))
}

newDates.sort((a, b) => {
  return b - a;
})

Jackson
  • 23
  • 4

2 Answers2

1

You could take a padded month value and sort by string after getting an ISO 8601 date.

var dates = [{ date: 'December 2016' }, { date: 'December 2017' }, { date: 'November 2016' }, { date: 'August 2015' }, { date: 'June 2018' }, { date: 'May 2017' }],
    months = { "January": '01', "February": '02', "March": '03', "April": '04', "May": '05', "June": '06', "July": '07', "August": '08', "September": '09', "October": '10', "November": 11, "December": '12' };

dates.sort(({ date: a }, { date: b }) => {
    const getDate = s => s.split(' ').reduce((m, y) => [y, months[m]].join('-'));
    
    return getDate(a).localeCompare(getDate(b));
});

console.log(dates);
.as-console-wrapper { max-height: 100% !important; top: 0; }
Nina Scholz
  • 323,592
  • 20
  • 270
  • 324
-1

A simple start would be to do this, wich isn't efficient but should be ok if your array is not huge:

let dates = [{ date: 'December 2016' }, { date: 'December 2017' }, { date: 'November 
2016' }, { date: 'August 2015' }, { date: 'June 2018' }, { date: 'May 2017' }];

dates.sort((a, b) => {
  const dateA = new Date(a.date.replace(' ', ', '));
  const dateB = new Date(b.date.replace(' ', ', '));
  return dateB - dateA;
});

If you intend to do the sorting frequently on large amounts of data, I'd recommend instead to convert your array to use numbers to represent the dates. You can then format them into <Month> <year> when you need to display them.

Joru
  • 4,153
  • 1
  • 17
  • 13