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.
const values = [10000, 20000, 25000, 5000]; // values per year sorted ascending
const increases = values.map((currVal, index) => {
if (index === 0) {
return;
}
const prevVal = values[index - 1];
return ((currVal - prevVal) / prevVal) * 100;
}).filter(Boolean);
console.log(increases); // [100, 25, -80] values in percent
This will return a list with your increase (%) from year to year.
The solution using Array.reduce function:
var sum = [35780, 96448, 48956],
diff = ['-']; // first column is empty '-'
sum.reduce(function (a, b) {
if (a === 0) return b;
var isNegative = b - a < 0;
diff.push(parseInt((b - a) / (isNegative? a : b) * 100));
return b;
}, 0);
console.log(diff); // ["-", 62, -49]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With