You need to enable JavaScript to run this app. 如何用JavaScript处理数组结合Chart.js生成每月分组计数统计图表
优惠活动
大模型
产品
解决方案
定价
更多

如何用JavaScript处理数组结合Chart.js生成每月分组计数统计图表

适配Chart.js横向条形图的月度分组计数汇总实现

实现原则

最终传入数据集的数组顺序,必须和图表配置里固定的12个月份标签(Jan到Dec)完全对齐,避免因部分月份无分组数据出现轴标签错位。

  • 预先按图表的月份顺序初始化两个分组的计数槽位,默认值为0
  • 遍历原始users数组,按条目的activity_type归属,把对应count累加到匹配的月份槽位
  • 按固定月份顺序提取槽位数值,生成dataset要求的data数组

可直接替换的代码逻辑

将以下汇总逻辑放在Chart实例化代码之前,替换原配置中空值的data字段即可:

// 统一月份顺序基准,和图表labels保持一致
const monthLabels = ["Jan", "Feb", "Mar", "Apr", "May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"];

// 初始化两个分组的全月份累加容器
const groupASummary = Object.fromEntries(monthLabels.map(month => [month, 0]));
const groupBSummary = Object.fromEntries(monthLabels.map(month => [month, 0]));

// 遍历原始数据做累加
users.forEach(item => {
  // 过滤字段不全的无效条目
  if (!item.activity_type || !item.month || typeof item.count !== 'number') return;
  if (item.activity_type === 'groupA') {
    groupASummary[item.month] += item.count;
  } else if (item.activity_type === 'groupB') {
    groupBSummary[item.month] += item.count;
  }
});

// 生成和labels顺序完全匹配的data数组
const groupAData = monthLabels.map(month => groupASummary[month]);
const groupBData = monthLabels.map(month => groupBSummary[month]);

// 实例化图表,替换原空的data字段
var ex_chart = new Chart(ct, {
  type: 'horizontalBar',
  data: {
    labels: monthLabels,
    datasets: [
      {
        label: 'groupA',
        data: groupAData,
        backgroundColor: '#C7CED7'
      },
      {
        label: 'groupB',
        data: groupBData,
        backgroundColor: '#0068B4'
      }
    ]
  },
  options: options
})

常见踩坑提示

  • 不能直接按users的遍历顺序拼接数据,否则无数据的月份会被跳过,后续数据会错位到前面的标签位置
  • 全月份初始0值的设计,可以保证哪怕某月份某分组没有任何计数,也会在对应位置占位,不会出现图表柱子偏移
  • 字段校验逻辑可以避免脏数据导致的NaN值出现在图表展示中

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.11.07 19:45:01