Logo

dev-resources.site

for different kinds of informations.

How to sort an array of month names -- Javascript

Published at
5/31/2023
Categories
javascript
beginners
webdev
programming
Author
NasreenKhalid
How to sort an array of month names -- Javascript

Hi there, so I was working with some dates and months arrays in javascript and came across this fact that if you sort an array of month names in javascript using the sort() method, it will sort the array in alphabetical order making 'April' the first month of the year which is not what we want. Following is the output when you simply use sort() method on an array of names in Javscript:



const months = ['January', 'March', 'February', 'May', 'June','April'];

months.sort()
console.log(months);


Below is the output:

Image description

So, what we should do is to define a new array which contains the names of the months in chronological order and then compare both the arrays and also we need to define a comparison function which will compare the indices of both the arrays using the indexOf method, the function will look like this:



const months = ['January', 'March', 'February', 'May', 'June','April'];

months.sort((a, b) => {
  const monthOrder = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'];
  return monthOrder.indexOf(a) - monthOrder.indexOf(b);
});

console.log(months);


The resulting array of 'months' will show the names in the correct order as we want:

Image description

Hope you find this article useful while brushing up your basic javascript skills.
Have a good time coding...

Featured ones: