我有一个我想要操作的数组,因为我需要将它用作D3.js的数据源。此数据集的一个示例是:
var data = [
{day: 1, month: 1, length: 100, year: 2010},
{day: 2, month: 1, length: 125, year: 2010},
{day: 3, month: 1, length: 150, year: 2010},
{day: 4, month: 1, length: 175, year: 2010},
{day: 1, month: 2, length: 225, year: 2010},
{day: 2, month: 2, length: 250, year: 2010},
{day: 3, month: 2, length: 325, year: 2010},
{day: 1, month: 1, length: 225, year: 2011},
{day: 1, month: 1, length: 150, year: 2011},
{day: 1, month: 1, length: 190, year: 2011},
{day: 1, month: 2, length: 210, year: 2011},
{day: 2, month: 2, length: 110, year: 2011},
{day: 3, month: 2, length: 160, year: 2011},
{day: 4, month: 2, length: 190, year: 2011},
]
在这种情况下,我想创建一个新数组,其中两个数组的平均长度为一个月。例如:
var newData = [ [137.5, 266.7], [183.33, 167.5] ]
newData [0] [1]将是2010年第1个月的平均长度。
我有一些问题以一种很好的方式融入其中。我可以创建长度的总和,但是除以总和是困难的。我的代码是:
data.forEach(function (el) {
for (var j = 0; j <= 3; j++) {
if (el.year === 2010 + j) {
for (var i = 1; i <= 2; i++) {
if (el.month === i) {
var oldLength = dataNew[j][i - 1] || 0;
var newLength = el.length + oldLength;
dataNew[j][i - 1] = newLength;
}
}
}
}
});
如何调整此函数,以便在newData中保存平均值而不是总和。
答案 0 :(得分:3)
您可以使用d3.js本身来方便您的工作并使您的代码更具可读性。使用d3.nest()
var data = [
{day: 1, month: 1, length: 100, year: 2010},
{day: 2, month: 1, length: 125, year: 2010},
{day: 3, month: 1, length: 150, year: 2010},
{day: 4, month: 1, length: 175, year: 2010},
{day: 1, month: 2, length: 225, year: 2010},
{day: 2, month: 2, length: 250, year: 2010},
{day: 3, month: 2, length: 325, year: 2010},
{day: 1, month: 1, length: 225, year: 2011},
{day: 1, month: 1, length: 150, year: 2011},
{day: 1, month: 1, length: 190, year: 2011},
{day: 1, month: 2, length: 210, year: 2011},
{day: 2, month: 2, length: 110, year: 2011},
{day: 3, month: 2, length: 160, year: 2011},
{day: 4, month: 2, length: 190, year: 2011},
]
var nest = d3.nest()
.key(function(d){return d.year})
.key(function(d){return d.month})
.rollup(function(d){
return d3.mean(d, function(g){return g.length});
})
.entries(data)
console.log(nest[0].values[0]) // 137.5
这是一个有效的fiddle