0
var months = ["April 2021","March 2021", "May 2021", "April 2020"];

how to get ascending order of these months of type string.

let monthArray = ["January", "Febraury", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"];

let preparedArray = [];

months.forEach(month => {
    let mntSplit = month.split(' ');
    preparedArray.push({year: mntSplit[1], month: mntSplit[0] });
});

how to proceed to asc sort please help

2
  • Can you post example of the output array which you want Commented Jun 1, 2021 at 12:51
  • resultExpected = ["April 2020","March 2021","April 2021","May 2021"] like this Commented Jun 1, 2021 at 12:55

2 Answers 2

3

Using sort() and Date() constructor

var months = ["April 2021", "March 2021", "May 2021", "April 2020"]

var sorted = months.sort((a, b) => new Date(a) - new Date(b))

console.log(sorted)

Update: (not working in firefox)

var months = ["April 2021", "March 2021", "May 2021", "April 2020"]

var sorted = months.sort((a, b) => new Date('01 ' + a) - new Date('01 ' + b))

console.log(sorted)

Sign up to request clarification or add additional context in comments.

3 Comments

not working in firefox browser
@ShaikHabeeb Sorry I never knew that. It's due to the date missing from the list.
hi, Can you explain to me what changed with the parameters ('01 ' + a) and ('01 ' + a) inside the new Data instance?
0

If you want to keep your code you can use this:

var months = ["April 2021","March 2021", "May 2021", "April 2020"];
let monthArray = ["January", "Febraury", "March", "April", "May", "June",
    "July", "August", "September", "October", "November", "December"];

months = months.sort((a,b)=>{
  const [monthA, yearA] = a.split(' '),
        [monthB, yearB] = b.split(' ');
  if (yearA === yearB)
    return monthArray.indexOf(monthA) - monthArray.indexOf(monthB);
  return +yearA - +yearB
})

console.log(months)

Otherwise sort by using new Date():

months.sort((a, b) => new Date(a) - new Date(b))

1 Comment

months.sort((a, b) => new Date(a) - new Date(b)) it is not working in firefox

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.