Listing of Months in Moment JS Array

I'm currently attempting to generate an array of months for the current quarter as well as the previous quarter using the code snippet below. I came across some guidance on this page and have been following it.

var dataQuarter =  Array.apply(null, Array(3)).map(function (_, i) {
        return moment(i, 'e').startOf('quarter').month(i).format('LL');
})

var dataQuarterLast =  Array.apply(null, Array(3)).map(function (_, i) {
        return moment(i, 'e').startOf('quarter').subtract(1, 'quarter').month(i).format('LL');
})

The content of the arrays generated by this code is not what I expected or desired. If anyone could point me in the right direction, I would greatly appreciate it.

Update:

Upon running console.log on both variables, here are the results:

Array(3) [ "January 1, 2020", "February 1, 2020", "March 1, 2020" ]

Array(3) [ "January 1, 2020", "February 1, 2020", "March 1, 2020" ]

Answer №1

To handle date and quarter manipulation in a custom function, you can map each quarter's three months into an array starting from the first month of the quarter and incrementing up to the following two months. Here is an example implementation:

const getMonthsPerQuarter = (date, quarter) => {
    return [0, 1, 2].map(value =>
        date.quarter(quarter)
            .startOf('quarter')
            .add(value, 'months')
            .format('LL')
    );
};

const date = moment('2020-02-27');     // Modify the date as needed.
const currentQuarter = date.quarter(); // Quarter ranges from 1 to 4.
const lastQuarter = 4;

const currentQuarterMonths = getMonthsPerQuarter(date, currentQuarter);
const lastQuarterMonths = getMonthsPerQuarter(date, lastQuarter);

console.log(currentQuarterMonths);
console.log(lastQuarterMonths);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.29.1/moment.min.js"></script>

If you execute this code, you will get the expected output. To display only the month names in the output array, replace 'LL' with 'MMMM'.

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

Transitioning away from bundled Javascript for local debugging

My current tasks on the gulpfile.js for my frontend app involve a serve task that handles the following: Processing less files Bundling all javascripts into dist/bundle.js Uglifying dist/bundle.js However, this setup made local debugging difficult. To a ...

Passing asynchronous data to child components using an object in Angular6

Currently, I am facing an issue with displaying data retrieved from a server using Angular 6, Rxjs, and Chartjs. When utilizing local mock data, everything works perfectly fine. However, when fetching data from the server, the charts render as blank becaus ...

Printing array elements in reverse order

Trying to debug my program, I need to print out all elements in the array. This is the loop for printing all elements of the array: for(int i = 0; i <= 9; i++) { printf("Words: %s\n", &words[i]); } In a header file, there's ...

JavaScript regular expression to switch menu

Could someone clarify the meaning of this code snippet: /expanded/.test(classes) I understand that the '/' characters indicate a regular expression and 'expanded' is a class name. However, I am unsure about what .test(classes) does ...

Creating a wrapper for methods of a third-party class in TypeScript

I have been working on creating a wrapper for all my third party API interfaces and SDKs that logs requests in a standardized yet customizable way. My approach involves passing the third party API (typically instantiated with a new API() call) into a wrapp ...

Tips for positioning large text next to an image

When creating a product detail page in HTML, I encountered an issue where adding large text to one div caused the entire page layout to shift. Does anyone know why this is happening? Could it be due to the size of the div not being defined? See the issue h ...

Working with AngularJS: binding data to dynamically appended HTML elements using JavaScript

Is there a way to connect an angular event and model to an html element that is added through javascript code? To see my code, click here: https://jsfiddle.net/hq7qk48n/13/ <div ng-app> <div ng-controller="MyController"> <input ...

Looking for guidance on utilizing pushState and handling onpopstate events?

By using ajax, I am able to load specific page content without refreshing the entire page. In order to make the back button functionality work, I utilize pushState and onpopstate as shown below: function get_page(args){ .... $.ajax({ url ...

Ways to retrieve the complete user object in passport

Recently, I've been diving into utilizing Express authentication with Passport and React for the frontend. While working on this project, a question came up: How can I access the entire authenticated user object? This is what my database model looks l ...

Creating fundamental forms using HTML, CSS, and Javascript

I am tasked with creating a unique web application where users can sketch and annotate simple shapes. The purpose of the app is to create basic store maps. These shape drawings must be saved in a database, including their coordinates, sizes, labels, and cu ...

Invoking a function within an HTML file does not result in triggering an alert message

Hello everyone, thank you for taking the time to look at this. I'm attempting to execute a javascript function when I click on the update button. Here is the javascript code: var text2Array = function() { // This function takes the value from the t ...

It appears that the event listener attached with the ".on()" method has suddenly ceased functioning

Starting off, here is a link to my project on jsfiddle I will discuss how it's supposed to work and the main issue I am facing. The project consists of three "lines" represented at the top by a selector box. Each line has different "parts" displayed ...

Deactivate the action triggered by a jQuery click event

$('document').ready(function(){ //textoverflow($('.content'),100); $('span').click(function(){ //disable textoverflow function & output full text }); }); function textoverflow(ele, num){ ele.each( ...

Running system commands using javascript/jquery

I have been running NodeJS files in the terminal using node filename.js, but now I am wondering if it is possible to execute this command directly from a JavaScript/jQuery script within an HTML page. If so, how can I achieve this? ...

How to add an OnClick listener to a cell element in a table built with the Tan

I am currently working on a project using React and trying to implement a table. I want to show an alert when a header cell in the table is clicked, displaying some information. However, I have been struggling to find assistance on adding a click listener ...

Prevent duplicate items in an array by utilizing the Map object to add elements

Looking for a way to update an array by adding new values while avoiding duplicates. I've implemented the usage of a Map object to keep track of existing values and tried filtering the new array accordingly. const [items, setItems] = useState([]); ...

I am looking for a way to retrieve the ids of all div elements that have the same x coordinate using document.elementFromPoint in JavaScript. Can someone help me with

Currently, I am facing an issue where I have two divs positioned at the same x coordinate. I am attempting to retrieve the IDs of both divs using document.elementFromPoint(). However, I am only able to receive the ID of one div. var elem = document.elem ...

Node.js is unable to effectively communicate signals with child processes

I've been diving into learning nodejs and exploring examples related to sending signals to child processes. In one particular scenario, I came across the following code snippets where handling "SIGINT" in the child process is supposed to trigger a res ...

What is the process for setting a default value in an array using Angular and then showcasing that value in a textbox?

I have been working on creating a form that includes a feature to dynamically append new rows. While I am able to successfully create new rows dynamically, I am facing an issue with displaying the initial values in my textboxes. Below is a snippet of my c ...

Unlocking the power of React using TypeScript for optimal event typing

I need assistance with properly typing events in TypeScript. Consider the following function: import * as React from 'react'; someHandler = (event: React.SyntheticEvent<HTMLInputElement> | React.KeyboardEvent<HTMLInputElement>) =&g ...