我有一个表格,显示一年中每个月的值。它看起来像:
Month | 2015 |
----------------
Jan | 4856 |
Feb | 6521 |
Mar | .... |
Apr | .... |
May | .... |
Jun | .... |
Jul | .... |
Aug | .... |
Sep | .... |
Oct | .... |
Nov | .... |
Dec | .... |
----------------
SUM | 48956 |
我有一个收集所有 SUM 值的数组,如下所示:
sum = [48956]
然后,用户可以选择向表中添加更多年份的值,例如:
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|
数组现在看起来像:
sum = [35780, 96448, 48956]
现在我希望“diff”行显示多年来百分比的增加或减少。
2014年与2013年相比,2015年与2014年相比等等..
我怎样才能捕获前任。数组中的 96448 和 35780 并计算 2014 年的差异值,然后将每个新年的相同值添加到表中?
96448 - 35780 = 60668 / 96448 = 0,629 * 100 = 62,9%
当然,第一年(本例中为 2013 年)没有差异。
最佳答案
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
这将返回一个列表,其中包含您每年的增幅 (%)。
关于javascript - 使用 Javascript 计算多个动态值的百分比变化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38092872/