Juank Juank - 2 months ago 5x
Javascript Question

Javascript - Asign values to month array

Having a result set of dates from an AJAX request, I want to create an array of length 12 that has the number of orders placed for each month of those dates, with the purpose of making charts with ChartJS.

For instance, if the DB has 12 orders placed in January, then the array will have the number 12 in its 0 index.

The problem is that my code looks awful this way, and if I want to do later for each day, I'll have a switch with 31 cases (that will look really messy).

The code works, but I want a more efficient way of doing this.

// Array with quantity of orders per month
var meses= [0,0,0,0,0,0,0,0,0,0,0,0];

for(var i in data) {
// Create new Date from each orderDate
var originalDate = data[i].orderDate;
var myDate= new Date(Date.parse(laFechaOriginal));
var elMes = myDate.getMonth();
// According to the month number, the same index number in the array will increment its value by 1
switch(elMes) {
case 0:
meses[0] += 1;
case 1:
meses[1] += 1;
case 2:
meses[2] += 1;
case 3:
meses[3] += 1;
case 4:
meses[4] += 1;
case 5:
meses[5] += 1;
case 6:
meses[6] += 1;
case 7:
meses[7] += 1;
case 8:
meses[8] += 1;
case 9:
meses[9] += 1;
case 10:
meses[10] += 1;
case 11:
meses[11] += 1;


There are definitely a few things you could improve in it, but they'll have a negligible effect on efficiency:

In modern engines you can replace your array initialization with Array.prototype.fill

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

If data is an array you should not use a for .. in loop to iterate through it. You could replace that with a normal counting loop:

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

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

 var myDate= new Date(laFechaOriginal);

You can replace that entire switch statement with: