I'm working with an array that needs manipulation in order to use it as a data source for D3.js. The dataset looks like this:
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},
]
My goal is to create a new array with average lengths per month. For example:
var newData = [ [137.5, 266.7], [183.33, 167.5] ]
In this array, newData[0][1] represents the average length of month 1 in year 2010.
I have managed to calculate the sum of lengths but struggle with getting the averages. Here's the code I currently have:
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;
}
}
}
}
});
I need help adjusting this function to store averages instead of sums in the newData array.