D3 V6中d3.nest分组函数等效写法及V3代码转V6实现
D3 V3嵌套分组代码升级至V6版本实现
以下实现完全对齐原V3版本的分组、排序逻辑,输出结构和原代码完全一致。
对应V6实现代码
// 写法1:Promise .then 写法 d3.csv('./data/d2.csv', d3.autoType) .then(data => { // 先对全量数据按price倒序,对应原sortValues逻辑 const sortedByPrice = data.sort((a, b) => b.price - a.price); // 两层嵌套分组+排序,对齐原nest逻辑 const nestedData = Array.from( d3.group(sortedByPrice, d => d.city), ([cityKey, cityValues]) => ({ key: cityKey, values: Array.from( d3.group(cityValues, d => d.type), ([typeKey, typeValues]) => ({ key: typeKey, values: typeValues }) ).sort((a, b) => d3.ascending(a.key, b.key)) // type字段正序排序 }) ).sort((a, b) => d3.descending(a.key, b.key)); // city字段倒序排序 console.log(nestedData); }); // 写法2:async/await 写法(更简洁) async function processData() { const data = await d3.csv('./data/d2.csv', d3.autoType); const sortedByPrice = data.sort((a, b) => b.price - a.price); const nestedData = Array.from( d3.group(sortedByPrice, d => d.city), ([cityKey, cityValues]) => ({ key: cityKey, values: Array.from( d3.group(cityValues, d => d.type), ([typeKey, typeValues]) => ({ key: typeKey, values: typeValues }) ).sort((a, b) => d3.ascending(a.key, b.key)) }) ).sort((a, b) => d3.descending(a.key, b.key)); console.log(nestedData); } processData();
如果不需要自动类型转换,也可以手动处理字段类型:
d3.csv('./data/d2.csv') .then(rawData => { // 手动转换数值类型 const data = rawData.map(item => ({ city: item.city, type: item.type, price: Number(item.price), id: Number(item.id) })); // 后续排序、分组逻辑和上述代码一致 })
核心改动说明
- d3.csv API调整:D3 v5及之后版本废弃了回调写法,统一返回Promise异步处理结果。第二个参数传入
d3.autoType可自动将CSV中数值类字段(price、id)转为Number类型,无需手动做类型转换。 - 嵌套分组API替换:D3 v6核心包移除了原
d3.nest方法,改用d3.group实现分组功能。d3.group返回Map结构,通过Array.from转换为数组后映射为原{key, values}格式,再对每层key做排序即可完全对齐原代码效果。
内容的提问来源于stack exchange,提问作者imonut
相关产品推荐
相关产品推荐

