Tips for representing entire months as object keys using numerical values

Currently, I find myself a bit puzzled as to why my code is not functioning as expected, and I am hopeful that you all could assist me in solving this issue.

The data structure I am working with consists of years and corresponding months.

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

I have a function designed to convert numerical values into their respective month names:

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

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

Within my code, there is an Object.keys method to display the year followed by the written out months on the screen.

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

At present, the output appears as follows:

2022: Invalid Date
2021: Invalid Date
2017: December

My query is: why does it show "Invalid Date" for some entries even though multiple numbers are specified for certain years, and how can I rectify this?

Answer №1

I made necessary modifications to ensure the code would run smoothly. The issue was related to passing a string of months instead of individual months. I updated the method to accept an array of months and added a sorting function to the sort() as well.

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

const displayMonthNames = function (monthArray, language) {
  let monthNames = [];

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

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

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

console.log(output);

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the reason for sending back an array with no elements in AJAX

I am facing a perplexing issue where my function is returning an empty array when it should contain values. This has me scratching my head, as initially the array 'storearray1' does contain values, but upon subsequent usage, it appears empty. I&a ...

Enable the x-axis months to be interactive in a chart.js line graph

Currently, I am in the process of developing a line chart using chart.js. The x-axis of the chart is time-based and represents months. I want to make each "month column" clickable/selectable, but I'm facing difficulty in achieving this functionality ...

Unveiling the Secrets of AJAX Requests with Enigmatic Strings Attached to URLs

My goal is to keep track of cricket scores on scorespro/cricket by utilizing browser AJAX requests. By analyzing the network traffic in Google Chrome, I have noticed that my browser sends out requests in this format: Whenever I click on the response withi ...

Finding the Modular Reciprocal with JavaScript

I am attempting to find the value of d by solving the equation ed ≡ 1 mod((p-1)(q-1)), similar to the RSA algorithm. Given e = 5 and (p-1)*(q-1) = 249996 I have experimented with various Javascript code snippets, such as: function calculateModInverse( ...

Exploring the concept of reflection in JavaScript and jQuery

Here is a javascript object I have: person.Name = "John"; person.Nick = "Smith"; person.Info = "hi there"; In addition, I have some HTML elements as shown below: <input id="Name" /> <input id="Nick" /> <input id="Info" /> My question ...

Tips for running Scrapy and Selenium on a webpage that utilizes angular JavaScript to serve data

I have been working on a web scraper that follows this process: Visit site A -> click on the buy now button -> redirected to Amazon -> scrape data -> return to site A The issue I am facing is that the site is built using AngularJS, and I am h ...

Issues with React Material UI Dialog Displaying Incorrect Information

As I experiment with React Material UI dialog boxes, I've encountered an issue that has me puzzled. I have an object 'a', and when I click on a button in a list, it should display the respective ID number. However, instead of showing the cor ...

Can a websocket be used to communicate with a server that is not the same as the one hosting the html5 website?

My goal is to establish communication between a hardware device and an HTML5 website. It seems like the best way to do this would be through WebSockets or possibly WebRTC over a WiFi network. Is that correct? I haven't come across any solutions invol ...

using javascript to access an opened html div

I am making an AJAX request in A.html and once the response is successful, I want to display a message in B.html. (The message should be displayed in a div with the id='mes_div' which is located in B.html.) How can I access B.html and how do I ac ...

Steps for assigning values to a JavaScript array using its indices

Question: Dynamically creating keys in javascript associative array Typically, we initialize an array like this: var ar = ['Hello', 'World']; To access its values, we use: alert(ar[0]); // Hello However, I am looking to assign ...

Function causing corruption in passed C char array

Currently, I am working on a project that involves a program similar to the game 20 Questions. In this program, a text file containing questions and answers is loaded and copied into a char array. I replace new space lines with '/0' in order to s ...

Creating an Array of dynamically generated elements using jQuery

A dynamic table is being generated using jQuery's .append() function: $el.append('<tr data-id=' + data[i].id + ' data-token=' + data[i].token + '><td>' + data[i].order + '</td>\n\<td&g ...

Foundation Unveil Modal hidden from view

I'm currently integrating modals using Foundation 5 in a Rails application. The issue I'm facing is that the modal only works when the page is not scrolled down. If you scroll to the bottom of the page and try to activate the modal by clicking ...

Rotate Text in HTML <thead> Tag

I need assistance with rotating a table header. https://i.stack.imgur.com/hcvxx.png The HTML th elements within the thead section are described as follows: <th> <span class="rotate-all">Period</span> </th> <th> < ...

Establishing a pair of separate static directories within Nest

I am looking to utilize Nest in order to host two static applications. Essentially, I have a folder structure like this: /public /admin /main Within my Nest application, I currently have the following setup: app.useStaticAssets(join(__dirn ...

utilizing various ajax functions

I'm having trouble using additional functions with the "complete:" option in JQuery ajax after the "selectOptionSort" function. Can anyone help me figure out what's wrong? $('#tipos').change(function(){ $("#marcas ...

Tips on elevating a dragged div above all other elements when utilizing two scrollbars

Currently, I have two horizontal scrollers where I need to drag a div from the upper scroller to the lower scroller. While this functionality is working properly, there is an issue with the dragged div getting lost under the borders of the scroller during ...

Learn the process of integrating VueJS with RequireJS

I am attempting to set up VueJS with RequireJS. Currently, I am using the following VueJS library: . Below is my configuration file for require: require.config({ baseUrl : "js", paths : { jquery : "libs/jquery-3.2.1.min", fullcalendar : "libs/ful ...

This error message in AngularJS indicates that the argument 'fn' is not being recognized as a function

I am currently working with angularjs and typescript and I am attempting to create a directive in the following manner: Below is my controller : export const test1 = { template: require('./app.html'), controller($scope, $http) { ...

Syncing data between parent and child components in VueJS using v-bind:sync with an object parameter for bidirectional data flow

In the app I am developing, there is a main component that passes an Object, specifically this.form, to a child form component using v-bind:sync="form". The child form then emits values for each key of the parent object on @input events. My goal is to be ...