Say that I've got this array:
testResults = [
{
dateCreated: "2014-07-12",
score: 27.1
},
{
dateCreated: "2014-05-11",
score: 99.3,
},
{
dateCreated: "2014-07-22",
score: 88.8
},
{
dateCreated: "2014-07-01",
score: 33.3
}
];
I want to create a function that:
takes testResults, startDate, endDate, and interval as arguments and calculates the average test results and returns an array as a result:
calculateTestAverages(testResults, "2014-04-01", "2014-07-30", "month");
would return
testAverages = [0, 99.3, 0, 49.7]
I think for now I want to just create an intermediary 2-D array:
intermediaryArray = [ [0], [99.3], [0], [27.1, 88.8, 33.3] ]
because calculating the average on this intermediary array will be easy.
What I've got so far does NOT work:
// takes a string date and converts it into a Date object.
var convertToDateObject = function(date){
dateObject = new Date(date);
return dateObject;
}
// takes a string date and returns the month.
var getMonth = function(date){
return convertToDateObject(date).getMonth();
}
var calculateTestAverages = function(testResults, startDate, endDate, interval){
var intermediaryArray = [];
if( interval == "month" ){
startingMonth = getMonth(startDate);
endingMonth = getMonth(endDate);
maxArrayIndex = endingMonth - startingMonth;
for (var i = 0; i <= maxArrayIndex; i++){
intermediaryArray[i] = [];
for (var month = startingMonth; month <= endingMonth; month++){
for (var testNumber = 0; testNumber < testResults.length; testNumber++){
if ( getMonth(testResults[testNumber].dateCreated) == month ){
intermediaryArray[i].push(testResults[testNumber].score);
};
};
};
};
};
return intermediaryArray;
}
I've been stuck on this thing for hours. I think my brain is kinda fried at this point.
calculateTestAverages(testResults, "04/01/2011", "07/30/2014", "month")do you mean the date to be04/01/2014because otherwise the answer doesn't make a lot of senseconvertToDateObjectworks as expected.05/11/2014can be confused with11/05/2014, this date format only depends on where you live. You should use an ISO date format likeYYYY-MM-DD(or others as explained here).convertToDateObjectis working as expected, but I will change it to ISODate.