gpt4 book ai didi

javascript - d3 中的分组和汇总

转载 作者:行者123 更新时间:2023-11-30 13:54:40 26 4
gpt4 key购买 nike

我的代码有问题。这是示例数据看起来像

var data = [
{
"office": "George Town Office",
"city_name": "George Town",
"total_employee": 2100,
},
{
"office": "George Town Working Space",
"city_name": "George Town",
"total_employee": 100,
},
{
"office": "Renasti KL Office",
"city_name": "Kuala Lumpur",
"total_employee": 1900,
}
]

我用键 (city_name) 将它分组,如果我需要计算 total_employee,我会遇到汇总问题。这是代码

var nested_data =  d3.nest()
.key(function(d) { return d.city_name; })
//error undefined .rollup(function(v, i) { return v.total_employee; })
.entries(da);

控制台结果示例如下

0:
key: "George Town"
values: Array(8)
0: {city_name: "George Town", office: "George Town Office", total_employee: 2100, …}
1: {city_name: "George Town", office: "George Town Office Working Space", total_employee: 100, …}

我的问题是如何计算同一个键中的 total_employee?预期结果

key: "George Town"
values: total_employee: 2200

最佳答案

在您的rollup 方法中...

.rollup(function(v, i) { return v.total_employee; })

... v 是一个对象数组,而不是单个对象。因此,您应该将其作为数组进行威胁,例如使用 d3.sum:

.rollup(function(v) {
return d3.sum(v, function(e) {
return e.total_employee;
})
})

这是演示:

var data = [{
"office": "George Town Office",
"city_name": "George Town",
"total_employee": 2100,
},
{
"office": "George Town Working Space",
"city_name": "George Town",
"total_employee": 100,
},
{
"office": "Renasti KL Office",
"city_name": "Kuala Lumpur",
"total_employee": 1900,
}
]

var nested_data = d3.nest()
.key(function(d) {
return d.city_name;
})
.rollup(function(v) {
return d3.sum(v, function(e) {
return e.total_employee;
})
})
.entries(data);

console.log(nested_data)
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>

关于javascript - d3 中的分组和汇总,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57544002/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com