Syntax error Sorting array of strings having year and month in JavaScript

Sorting array of strings having year and month in JavaScript



Suppose, we have an array of Strings that contains month-year combined strings like this −

const arr = ["2009-feb", "2009-jan", "2010-mar", "2010-jan", "2011-jul",
"2011-sep", "2011-jan", "2012-jan", "2012-dec", "2012-feb", "2013-may",
"2013-jul", "2013-jun", "2014-jan", "2014-dec", "2014-may", "2015-may",
"2015-jan", "2015-jun", "2016-jan", "2016-dec"];

We are required to write a JavaScript function that takes in one such array and sorts these dates in oldest to latest order.

Example

The code for this will be −

const arr = ["2009-feb", "2009-jan", "2010-mar", "2010-jan", "2011-jul",
"2011-sep", "2011-jan", "2012-jan", "2012-dec", "2012-feb", "2013-may",
"2013-jul", "2013-jun", "2014-jan", "2014-dec", "2014-may", "2015-may",
"2015-jan", "2015-jun", "2016-jan", "2016-dec"];
const sorter = (a, b) => {
   const getDate = date => {
      let day = date.split('-');
      day[1] = {
         jan: 1, feb: 2, mar: 3, apr: 4, may: 5, jun: 6, jul: 7, aug: 8, sep: 9, oct: 10, nov: 11, dec: 12
      }
      [day[1]
      .substring(0, 3)
      .toLowerCase()] || 0;
      return day;
   }
   const aDate = getDate(a);
   const bDate = getDate(b);
   return aDate[0] - bDate[0] || aDate[1] - bDate[1];
}
arr.sort(sorter);
console.log(arr);

Output

And the output in the console will be −

[
   '2009-jan', '2009-feb',
   '2010-jan', '2010-mar',
   '2011-jan', '2011-jul',
   '2011-sep', '2012-jan',
   '2012-feb', '2012-dec',
   '2013-may', '2013-jun',
   '2013-jul', '2014-jan',
   '2014-may', '2014-dec',
   '2015-jan', '2015-may',
   '2015-jun', '2016-jan',
   '2016-dec'
]
Updated on: 2020-11-21T10:07:03+05:30

246 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements