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

JavaScript中计算堆叠柱状图单柱多数据集数据总和的方法

计算堆叠柱状图单根柱子的总和

首先补全你的chartdata结构(原代码缺失闭合括号,会导致语法错误):

var chartdata = {
  labels: [
    "Bar 1",
    "Bar 2",
    "Bar 3",
    "Bar 4",
  ],
  datasets: [
    {
      label: "Green data",
      type: "bar",
      data: [20, 30, 40, 20]
    },
    {
      label: "Red data",
      type: "bar",
      data: [10, 30, 20, 10]
    },
    {
      label: "Blue data",
      type: "bar",
      data: [20, 20, 20, 20]
    }
  ]
};

方法一:动态匹配柱子名称(推荐)

通过labels数组找到目标柱子的索引,再遍历所有数据集累加对应位置的数值:

// 获取"Bar 1"在labels中的索引
const targetBarIndex = chartdata.labels.indexOf("Bar 1");
// 累加所有数据集对应索引的数值
const barTotal = chartdata.datasets.reduce((sum, dataset) => {
  return sum + dataset.data[targetBarIndex];
}, 0);

console.log(barTotal); // 输出:50

方法二:直接使用固定索引

如果确定"Bar 1"始终是第一个柱子(索引为0),可以简化代码:

const barTotal = chartdata.datasets.reduce((sum, ds) => sum + ds.data[0], 0);
console.log(barTotal); // 输出:50

关键说明

  • reduce方法用来遍历所有数据集,逐个提取对应柱子的数值并累加,初始值0确保即使数据集为空也不会返回NaN
  • 动态匹配索引的方式更灵活,当labels顺序调整或新增柱子时,不需要修改索引数值

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.29 23:48:27