I need a Google script (GAS) to retrieve both emails and total scores from a Google Form that was turned into a quiz.
Within GAS you can get the score for each quest
Your script is very close.
As there isn't a method to get at once all the item scores, one alternative is to build an array of item scores, then calculate the average for the each quiz (submitted response).
Example:
The following script, intended to be used as a bounded script, include three functions:
function onOpen(e) {
var ui = FormApp.getUi();
var menu = ui.createMenu('My Menu')
.addItem('Average', 'showAverage')
.addToUi();
}
function showAverage(){
// Works for bounded scripts called from custom menus or the script editor
var form = FormApp.getActiveForm();
Logger.log(calculateAverage(form));
}
/**
* Calculate the average score for each submitted response
*
* @param {Object} form The form to be processed.
* @return {Array} 2D array. First column respondent email,
* second column response average.
*/
function calculateAverage(form){
var formResponses = form.getResponses();
// If there aren't submitted responses, exit.
if(formResponses.length == 0) return 'No responses';
// Initialize output
var output = [];
for(var i = 0; i < formResponses.length ; i++){
var itemResponses = formResponses[i].getGradableItemResponses();
// Initialize scores array. Later it will be used to calculate the score average.
var scores = [];
for(var j = 0; j < itemResponses.length; j++){
var score = itemResponses[j].getScore();
scores.push(score);
}
// Average calculation. Reference https://stackoverflow.com/a/10624256/1595451
var sum = scores.reduce(function(a, b) { return a + b; });
var avg = sum / scores.length;
// Add row
var email = formResponses[i].getRespondentEmail();
output.push([email,avg]);
}
return output;
}
Reference