Sort array by month-year JavaScript

JavascriptWeb DevelopmentFront End TechnologyObject Oriented Programming

Suppose, we have an array that contains dates in MM-YYYY format like this −

const arr = ["1-2016", "7-2015", "7-2016", "3-2016", "8-2016", "2-2016", "6-2016", "8-2015", "5-2016", "4-2016", "9-2015", "10-2015", "11-2015", "12-2015"];

We are required to write a JavaScript function that takes in one such array and sorts it such that the dates in the array are arranged in oldest to newest order.

Example

The code for this will be −

const arr = ["1-2016", "7-2015", "7-2016", "3-2016", "8-2016", "2-2016", "6-2016", "8-2015", "5-2016", "4-2016", "9-2015", "10-2015", "11-2015", "12-2015"];
const padToString = (num) => {
   return String("0" + num).slice(-2);
};
const sortByDate = (first, second) => {
   const firstPart = first.split('-'), secondPart = second.split('-');
   const a = firstPart[1]+padToString(firstPart[0]);
   const b = secondPart[1]+padToString(secondPart[0]);
   return a - b;
};
arr.sort(sortByDate);
console.log(arr);

Output

And the output in the console will be −

[
   '7-2015', '8-2015',
   '9-2015', '10-2015',
   '11-2015', '12-2015',
   '1-2016', '2-2016',
   '3-2016', '4-2016',
   '5-2016', '6-2016',
   '7-2016', '8-2016'
]
raja
Published on 23-Nov-2020 10:10:57
Advertisements