Google script to get averaged scores and emails from Google Forms (as Quiz)

前端 未结 1 1028
伪装坚强ぢ
伪装坚强ぢ 2021-01-16 10:35

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

1条回答
  •  抹茶落季
    2021-01-16 10:52

    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:

    • onOpen Adds a custom menu
    • showAvarage the main function that sets the form to be processed and calls the function that creates a 2D array. It could be used to send the values to a spreadsheet, but for simplicity this was omitted.
    • calculateAvarage Collects the respondents emails and calculates the average score for each quiz (response submission)
    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

    • Array Sum and Average

    0 讨论(0)
提交回复
热议问题