Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

105
Views
how to write out entire months with object key where the months are in numbers

Currently I'm slightly confused why my code is not working as intended, and I was hoping you guys would be able to help me.

I have an object with year and months.

chosenMonths = {[
    2022: [0,1,2]
    2018: [9,10]
    2017: [11]
]}

I have a function that will convert the number into written out months:

const writeOutMonth = function(num, locale) {
    const date = new Date();
    date.setMonth(num);

    return date.toLocaleString(locale, {month: 'long',});
}

And inside my code I have an Object.keys where I want to print out the year and then the written out months on the page.

${Object.keys(chosenMonths).reverse().map((year) => html`<p1> ${year}: ${writeOutMonth(chosenMonth[year].sort().join(', '), 'en-gb')}</p>`)} 

Right now, I see it will render:

2022: Invalid Date
2021: Invalid Date
2017: December

My question is: why is it Invalid Date, when I have multiple numbers in a year, and how do I make it work?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

I had to made modifications to make the code run, I believe that's what you need, the problem was that you were passing a string composed of months, instead of passing a month, I change the method to receive an array og months, also, to the sort() I had to the add the sorting function

chosenMonths = {
  2022: [0, 1, 2],
  2018: [9, 10],
  2017: [11],
};

const writeOutMonth = function (monthArray, locale) {
  let monthNames = [];

  monthArray.forEach((mon) => {
    const date = new Date();
    date.setMonth(mon);
    monthNames.push(date.toLocaleString(locale, { month: "long" }));
  });

  return monthNames.join(", ");
};

let result = Object.keys(chosenMonths)
  .reverse()
  .map(
    (year) =>
      `<p1> ${year}: ${writeOutMonth(
        chosenMonths[year].sort((a, b) => a - b),
        "en-gb"
      )}</p>`
  );

console.log(result);
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!