You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过循环计算数组中子数组的数值差值,实现月均变化统计?

解决方案

1. 循环计算相邻子数组的差值

你可以通过for循环遍历数组,从第2个子数组开始,依次计算当前子数组的第二个元素与前一个子数组第二个元素的差值,将结果存入新数组:

let groupedMonthTotals = [
  [867884, 984655], [322013, -69417], [310503, 522857],
  [1033096, 604885], [-216386, 477532], [893810, -80353]
];

// 存储差值的空数组
let differences = [];

// 从索引1开始遍历(对比当前子数组与前一个)
for (let i = 1; i < groupedMonthTotals.length; i++) {
  // 前一个子数组的第二个值(如第2月数据)
  const prevSecondValue = groupedMonthTotals[i - 1][1];
  // 当前子数组的第二个值(如第4月数据)
  const currSecondValue = groupedMonthTotals[i][1];
  // 计算差值并推入数组
  differences.push(currSecondValue - prevSecondValue);
}

console.log(differences);
// 输出:[-1054072, 592274, 82028, -127353, -557885]

2. 计算月均变化值

每个差值代表两个月跨度的总变化,因此月均变化值为差值除以2,你可以用map方法快速生成月均数组:

let monthlyAvgChanges = differences.map(diff => diff / 2);

console.log(monthlyAvgChanges);
// 输出:[-527036, 296137, 41014, -63676.5, -278942.5]

3. 计算年度总平均值

年度总平均值即所有月均变化值的算术平均,通过求和后除以月均数组的长度即可:

// 计算所有月均变化的总和
const totalSum = monthlyAvgChanges.reduce((sum, val) => sum + val, 0);
// 计算年度总平均
const annualTotalAvg = totalSum / monthlyAvgChanges.length;

console.log(annualTotalAvg);
// 输出:-106500.8

内容的提问来源于stack exchange,提问作者BuiltByDan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.08 10:25:21