
- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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' ]
- Related Questions & Answers
- Sort array by year and month JavaScript
- Sorting array of strings having year and month in JavaScript
- Sort by index of an array in JavaScript
- Group month and year in MySQL?
- MySQL query to get result by month and year based on condition?
- Sort array of objects by string property value - JavaScript
- Sort Array of objects by two properties in JavaScript
- Finding day of week from date (day, month, year) in JavaScript
- Display Month of Year using Java Calendar
- Sort array of objects by string property value in JavaScript
- How to sort array by first item in subarray - JavaScript?
- Sort an array of objects by multiple properties in JavaScript
- Sort Array By Parity in Python
- Sort MongoDB Collection by Array value?
- MySQL datatype to store month and year only?
Advertisements