我正在努力理解如何使用新的 d3.group and d3.groups methods .我的目标是向我的 d3.chart 添加一个下拉菜单。具体来说,当我选择一个选项时,图表会显示该特定个人的数据。我的问题是我不明白如何访问所选个人的内部数组。例如,如果我选择 bib nr。 5,我想访问这个人的比率分数。
这个问题困扰我好久了。感谢您的帮助:)
const data = d3.range(20).map(i => ({
bib: Math.floor(i / 5) + 1,
ratio: -1 + Math.random() * 5,
run: [1, 2, 3, 4, 5][i % 5],
name: ['GIRL1', 'GIRL2', 'GIRL3', 'GIRL4'][Math.floor(i / 5)]
}));
// Now I want to use d3.groups
const skiers = d3.groups(data, d => d.bib)
//Logging this gives me a nested array.
console.log(skiers)
// I want to access the inner array for a particular individual, but how can I accomplish this?
// I have tried to use .map()
console.log(skiers.map(d => d.run)) //This gives me undefines
<script src="https://unpkg.com/d3@6.2.0/dist/d3.min.js"></script>
最佳答案
使用filter()
获取 d[0]
等于您要收集的 bib
的所有对象;
const data = d3.range(20).map(i => ({
bib: Math.floor(i / 5) + 1,
ratio: -1 + Math.random() * 5,
run: [1, 2, 3, 4, 5][i % 5],
name: ['GIRL1', 'GIRL2', 'GIRL3', 'GIRL4'][Math.floor(i / 5)]
}));
const skiers = d3.groups(data, d => d.bib)
const bibToFind = 3;
// Array with objects
const bibFound = skiers.filter(d => d[0] === bibToFind);
// Objects only
const bibObjects = bibFound[0][1];
console.log(bibFound, bibObjects);
<script src="https://unpkg.com/d3@6.2.0/dist/d3.min.js"></script>
关于javascript - 如何访问 d3.groups 产生的内部数组?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65478507/