英文:
How to sum up multiple datasets [0, 1, 2, 3, 4...] with always data [0] in Javascript
问题
我仍然是一名新手,需要一些帮助。
这是我的变量 chartdata 作为起点:
var chartdata = {
labels: [
"Bar 1",
"Bar 2",
"Bar 3",
"Bar 4",
],
datasets: [
{
label: "绿色数据",
type: "bar",
data: [20, 30, 40, 20]
},
{
label: "红色数据",
type: "bar",
data: [10, 30, 20, 10]
},
{
label: "蓝色数据",
type: "bar",
data: [20, 20, 20, 20]
},
]
}
因为我有一个堆叠的条形图,我想知道如何求和"Bar 1" 的数据点,它们分别是 20、10、20 = 50。
我最初考虑使用数组,代码如下:
const array0 = chartdata.datasets[0].data;
console.log(array0.reduce((a, b) => a + b, 0));
...但它只能将 20 + 30 + 40 + 20 相加,这是数据集[0]内的所有数据和类似的操作。这意味着我只能获取所有绿色数据点或其他数据点的总和,而不是一个堆叠条的总和。
似乎不可能创建类似 chartdata.datasets[0 到 4].data[总是 0] 的东西,它代表了y轴上"Bar 1"的总值。
我尝试使用 .map 来设置一些东西,但我无法自己完成。
也许您,专家,可以为我提供一个直接可运行的解决方案。
提前感谢您。
英文:
I am still a rookie and need some help.
There is my variable chartdata as starting point:
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]
},
As I have a stacked barchart. I want to know how I can sum the "Bar 1" datapoints which are 20, 10, 20 = 50.
I first thought about an array and it was like this:
const array0 = chartdata.datasets[0].data;
console.log(array0.reduce((a, b) => a + b, 0));
...but it could only add 20 + 30 + 40 + 20, which is all the data within dataset[0] and similar operations. Means I can only get all Green datapoints or others. Not the total sum for one stacked bar.
It did not seem possible to make something like chartdata.datasets[0 to 4].data[always 0]; which is the tota l val"bar 1" value on the y-axis.
I tried to set up something with .map, but I could not really do it on my own.
Maybe you, experts, can provide me a solution which I can directly run.
Thanks in advance.
答案1
得分: 1
使用 Array#reduce
在 chartdata.datasets
上进行操作。
let 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]},]};
let res = chartdata.datasets.reduce((acc, curr) => acc + curr.data[0], 0);
console.log(res);
英文:
Use Array#reduce
over chartdata.datasets
itself.
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
let 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]},]};
let res = chartdata.datasets.reduce((acc, curr) => acc + curr.data[0], 0);
console.log(res);
<!-- end snippet -->
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论