1

I have a list of months that are pulled into my Vue app. I would like to display them in chronological order. Jan, Feb, March etc

I have read another post that shows a way to do this if you just use the data from the page.

data: function () {
return {
  monthNames: [
    { month: "January", position: "01" },
    { month: "February", position: "02" },
    { month: "March", position: "03" },
    { month: "April", position: "04" },
    { month: "May", position: "05" },
    { month: "June", position: "06" },
    { month: "July", position: "07" },
    { month: "August", position: "08" },
    { month: "September", position: "09" },
    { month: "October", position: "10" },
    { month: "November", position: "11" },
    { month: "December", position: "12" },
   ], 
 This is part of the method I use to split and sort the data which is pulled in using an Axios request. It sorts it in alphabetical order though. 

    methods: {

     let startdate = [];
          metastartdate.forEach((item) => {
            const splitArr = item.split(", ");
            startdate = startdate.concat(splitArr).sort();
          });
 

Can anyone help me to work this out? 
  • Does this answer your question? [Sort array of objects by string property value](https://stackoverflow.com/q/1129216/328193) – David Oct 26 '22 at 15:12
  • We can't help you if we don't know how your data looks like. From your question I assume it is a string like "Jan, Feb, Oct..." and it has nothing to do with the json you posted above? – Vojin Purić Oct 26 '22 at 15:15

1 Answers1

0

If you just have an array of month names, you can parse the month to a date, and then create a new Date() and then use the .getMonth() extension to get the month number. You can then sort the array by that month number.

In the snippet below I created a method to get the month number from a string and used it in the Array.sort() method.

let months = ['November', 'Jan', 'Dec', 'April', 'Sept', 'March', 'Sep' , 'June', 'Febr'];

const getMonthNumber = (month) => new Date(Date.parse(`01 ${month}`)).getMonth();

let sorted = months.sort((a,b) => getMonthNumber(a) - getMonthNumber(b) );

console.log(sorted);
Steve
  • 878
  • 1
  • 5
  • 9