Skip to content
Advertisement

Accumulate monthly totals while looping

I have an array of data containing monthly amounts from the current year and the previous year. The previous year always has all of its amounts, but when a current/future month in the current year is iterated it has a null value. Here is an example:

JavaScript

This is my current code

JavaScript

How can I roll previous month amounts into current month to keep a running total month-to-month for each year? Also, as soon as a month returns a null amount, all previous amounts should be dropped and the month should show null for the rest of the year.

Desired output (assuming the current month is February):

JavaScript

Advertisement

Answer

I am assuming that you are dealing with integer values and your commas represent thousands placeholders. These need to be sanitized to allow the addition to take place.

I have included the null checks and it assumes that once a null date is encountered in the current year, there won’t be a subsequent numeric value.

Code: (Demo)

JavaScript
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement