JavaScript - Populate an array with values for each month

After receiving a list of dates from an AJAX request, I am aiming to generate an array containing the number of orders placed for each month. This data will be used to create charts using ChartJS.

For example, if there were 12 orders made in January, the array would have the number 12 stored at index 0.

The issue lies in my current code structure; it appears messy and inefficient, especially when considering expanding it to track daily orders with multiple switch cases.

Although the existing code is functional, I am seeking a more streamlined and efficient approach.

                // Array storing order quantity per month
                var monthsArray = [0,0,0,0,0,0,0,0,0,0,0,0];

                for(var i in data) {
                    // Creating a new Date object from each orderDate
                    var originalDate = data[i].orderDate;
                    var myDate = new Date(Date.parse(originalDate));
                    var monthIndex = myDate.getMonth();
                    // Incrementing the value at the corresponding index in the array based on the month number
                    meses[monthIndex] += 1;
                }

Answer №1

There are a few areas that could be enhanced, although they may only have a minimal impact on performance:

In modern JavaScript engines, you have the option to utilize Array.prototype.fill for array initialization:

var months = Array(12).fill(0);

If your data variable is an array, it's recommended not to use a for ... in loop for iteration. Instead, consider a standard counting loop like this:

for (var i = 0; i < data.length; i++)

The Date constructor already implicitly calls Date.parse, so you can omit the explicit call to Date.parse:

var myDate = new Date(originalDate);

You can simplify the switch statement with this code snippet:

months[currentMonth]++;

Answer №2

To retrieve the element from the array, simply use the variable as the index:

months[theMonth] += 1;

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

Utilizing React Native for seamless deep linking with automatic fallback to a webpage, including the ability to pass

I am currently working on a project that involves a website built with React and a React-native app for camera functionality and data processing. On the website, there is a button that opens the camera in the React-native app through deep-linking. This pa ...

My navbar list elements are not functioning properly due to an issue with JS. Does anyone have a solution to resolve this issue

As I work on creating a website using a free template, I encountered an issue with JS that I am not very familiar with. After conducting some research, it seems like the problem lies within the JS code. Below are the relevant snippets of HTML and JS code: ...

What is the best way to extract values exclusively from a JSON array using jQuery?

Struggling to extract values from a JSON array, I've scoured Stack Overflow for solutions but haven't found the right one. This is what my code looks like: .done(function (data) { var jdata = JSON.stringify(data['queryBuilder']); ...

What is the process for automatically saving associated models when saving the main model?

In my quiz manager, I am working on allowing users to add questions and edit the answers for those questions. My goal is to have a single save button that saves both the questions and their corresponding answers. However, when trying to access and call the ...

Analyzing component variable using Jasmine testing

When using spyOn in a jasmine test to monitor a function call from a service that returns an Observable, I encountered the error "unexpected token U JSON." This error originated from this line within the component: this.config = JSON.parse(localStorage.g ...

Cursor starts to move to the front of the input line after every single letter with a 1 millisecond delay while browsing certain websites, such as the comments section on Youtube

When I type a letter in the field, within 1 millisecond the cursor jumps to the beginning of the line in the typing field, causing text to be typed in reverse. I can only send messages on certain sites, such as YouTube comments and Yandex Translate, for ex ...

Unique Google Map Marker Description customization

I need assistance with customizing the description portion of the Google Maps marker description parameter. "title": '<%# Eval("country") %>', "lat": '<%# Eval("Latitude") %>', "lng": '<%# Ev ...

Generating combinations of numbers from sets of indexes

If I have a numpy array and want to create tuples of triplets, quadruplets, or quintuplets from pairs of indices meeting certain criteria, how can I accomplish this? For instance, if we consider the example provided where pairs_tuples is [(1, 0), (3, 0), ...

Validation of decimal numbers in JavaScript without the presence of any other characters

Looking to create a JavaScript regex to validate an 8-digit number that may include decimals. The current regex /^\d+$/ allows for any other characters such as ( , * $ etc. How can I modify this to only accept numbers and periods? For example, the nu ...

Error: The property 'fixtures' of an undefined object cannot be accessed. This issue arose from trying to access nested JSON data after making

Struggling with asynchronous calls, JS, or React? Here's my current challenge... Currently, I am using the fetch library to display a table based on data structured like this (note that there are multiple fixtures within the fixtures array): { " ...

How can one identify and remove a substring from a larger string in C++ while keeping the rest of the original string stored in a different variable?

I am currently developing a function that is receiving a line (in string format) from a file. Each line in the file starts with a line number followed by a command, as shown below: 1 commandX hello 2 commandY world ... 12 commandZ yes The ...

Guide to effectively invoking JavaScript functions using jQuery

<head> <script src="jquery-latest.js" /> <script> function resetValues(){ alert('Inside the resetValues function'); //using hexadecimal routine 1 -> 3 -> 5 -> 8 -> (11 == a) document.getElementB ...

Using JavaScript to pre-select a radio button without any user interaction

Is there a way to programmatically set a radio button in a group without physically clicking on the button? I am attempting to open a jQuery page and depending on a stored value, the corresponding radio button should be selected. I have researched similar ...

transferring data from a form with a binary image file to store in an SQL server

I am aiming to create a form where users can upload an image along with some data fields. Currently, I can only get either the image or the data fields to work separately. The following code allows me to upload an image to my SQL database as binary data. I ...

Is there a way to reverse the effects of calling preventDefault() during a touchmove event

if ((element).classList.contains('modal-open')){ document.documentElement.removeEventListener("touchmove", function(e) { e.preventDefault(); }, false); } I need help removing the preventDefault(); function when the modal is closed. ...

Create an array populated with unclosed HTML tags that need to be rendered

I'm trying to display a simple list, but it seems like React is having trouble rendering unclosed HTML elements that are pushed onto the list. This results in an error: ReferenceError: el is not defined If I use single quotes (') bookingStat ...

Accessing data from arrays asynchronously using JavaScript

Update I have included actual code below, in addition to the concept provided earlier. Here is the async array access structure I am trying to implement: for (p = 0; p < myList.length ; p++){ for (k = 0; k < RequestList.length; k++){ i ...

How to dynamically insert a key into an array by locating a specific value in AngularJS

I need help adding a new key to a JSON array by searching for a specific key value. For example JSON:- [ { "$id": "2025", "ID": 41, "Name": "APPLE" }, { "$id": "2026", "ID": 45, "Name": "MANGO" }, { "$id": "2027", ...

Instructions on merging elements in an array with identical property values

Consider the array below: [{a:1,b:1},{a:5,b:2},{a:10,b:2},{a:20,b:3}] Is there a way to create a new array that merges elements with the same b value, while adding up the corresponding a values? The desired output should be as follows: [{a:1,b:1},{a:(5+10 ...

Searching for specific values within a multidimensional array using PHP

I need to create a PHP page that can show the BackupJobs from the past week. The backup-jobs are fetched from an API and stored in JSON format. I am encountering an issue when I have a specific BackupSetID and want to display all corresponding BackupJobs ...