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:
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:
Hope you find this article useful while brushing up your basic javascript skills.
Have a good time coding...
Top comments (2)
Interesting approach - thanks for sharing!
One potential disadvantage is that
indexOf
has to be called multiple times. One way around that might be to declare the order in an object, e.g.That said, the performance impact for small lists like this is probably negligible.
Thank you for sharing this :)