- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Sort array by month-year JavaScript
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' ]
Advertisements