Sort array by year and month JavaScript

JavascriptWeb DevelopmentObject Oriented Programming

We have an array like this −

const arr = [{
   year: 2020,
   month: 'January'
}, {
   year: 2017,
   month: 'March'
}, {
   year: 2010,
   month: 'January'
}, {
   year: 2010,
   month: 'December'
}, {
   year: 2020,
   month: 'April'
}, {
   year: 2017,
   month: 'August'
}, {
   year: 2010,
   month: 'February'
}, {
   year: 2020,
   month: 'October'
}, {
   year: 2017,
   month: 'June'
}]

We have to sort this array according to years in ascending order (increasing order). Moreover, if there exist two objects with the same year property, then we have to sort those years according to month (like jan, then feb, then march and so on).

So, let’s write the code for this sorting problem. The complete code for this will be −

Example

const arr = [{
   year: 2020,
   month: 'January'
}, {
   year: 2017,
   month: 'March'
}, {
   year: 2010,
   month: 'January'
}, {
   year: 2010,
   month: 'December'
}, {
   year: 2020,
   month: 'April'
}, {
   year: 2017,
   month: 'August'
}, {
   year: 2010,
   month: 'February'
}, {
   year: 2020,
   month: 'October'
}, {
   year: 2017,
   month: 'June'
}]
const months = ['January', 'February', 'March', 'April', 'May', 'June',
'July', 'August', 'September', 'October', 'November', 'December'];
const sorter = (a, b) => {
   if(a.year !== b.year){
      return a.year - b.year;
   }else{
      return months.indexOf(a.month) - months.indexOf(b.month);
   };
};
arr.sort(sorter);
console.log(arr);

We check if the years are different, we just sort them according to years, but when the years are the same, we check for months taking help of the custom months array we defined and this way, objects with the same year get sorted according to months.

Output

The output in the console will be −

[
   { year: 2010, month: 'January' },
   { year: 2010, month: 'February' },
   { year: 2010, month: 'December' },
   { year: 2017, month: 'March' },
   { year: 2017, month: 'June' },
   { year: 2017, month: 'August' },
   { year: 2020, month: 'January' },
   { year: 2020, month: 'April' },
   { year: 2020, month: 'October' }
]
raja
Published on 20-Aug-2020 06:48:01
Advertisements