Anton Bollen Forsberg Anton Bollen Forsberg - 5 months ago 11
Javascript Question

Calculate percent change over multiple dynamic values with Javascript

I have a table displaying values for each month over a year. It looks something like:

Month | 2015 |
----------------
Jan | 4856 |
Feb | 6521 |
Mar | .... |
Apr | .... |
May | .... |
Jun | .... |
Jul | .... |
Aug | .... |
Sep | .... |
Oct | .... |
Nov | .... |
Dec | .... |
----------------
SUM | 48956 |


I have an array collecting all the SUM values like this:

sum = [48956]


The user can then choose to add more years of values to the table like:

Month | 2013 | 2014 | 2015 |
----------------------------------
Jan | 6587 | 8954 | 4856 |
Feb | 1254 | 1125 | 6521 |
Mar | .... | .... | .... |
Apr | .... | .... | .... |
May | .... | .... | .... |
Jun | .... | .... | .... |
Jul | .... | .... | .... |
Aug | .... | .... | .... |
Sep | .... | .... | .... |
Oct | .... | .... | .... |
Nov | .... | .... | .... |
Dec | .... | .... | .... |
----------------------------------
SUM | 35780 | 96448 | 48956 |
----------------------------------
diff | | %change| %change|


The array now looks like:

sum = [35780, 96448, 48956]


Now i want the "diff" row to show the increase or decrease in percentage over the years.

2014 compared with 2013, 2015 compared with 2014 and so on..

How can i grab ex. 96448 and 35780 in the array and calculate the diff value for 2014, and then the same for each new year added to the table?

96448 - 35780 = 60668 / 96448 = 0,629 * 100 = 62,9%


Ofcourse the first year (2013 in this case) has no diff.

Answer

Following example has the condition, that your year values are sorted ascending in your array (here arr):

var arr = [10000, 20000, 25000, 5000];

var diffs = [];
var previousYearVal;

arr.map(function(yearVal) {
    if(previousYearVal){
        diffs.push( ((yearVal - previousYearVal) / yearVal) * 100 );
    }

    previousYearVal = yearVal;
});

console.log(diffs); // [50, 20, -400] values in percent

Which will return a diffs array with the values sorted as they come in your sum array, meaning the first value represents the diff for the first two year value in your array (in my example 10000, 20000).

But if you working with data like this, i would try using an Object instead, which will make life easier for you calculating and referencing the years.

For example you should think about a structure like this:

{
    years: {
       2015: [ JanuaryValue, FebruaryValue ... ],
       2016: [ ... ]
    }
    differenceToYearBefore: {
       2015: diffValue,
       2016: diffValue
    }
}

If you have it like this, you could then more easily iterate through your object while using the keys to access the right values to read / write instead of iterating through arrays without knowing exactly which value you are currently accessing (without the "rules in your head").