Start a conversation

Calculate the average of several non-required variables

Sometimes you want to calculate the average of several variables, but some of them are non-required and can thus be left empty. But you still want to calculate the average from all *answered* variables. To do that, you have to calculate how many were actually answered and then calculate the average (as a sum of all of them divided by their number).

This applies to numerical fields, but also to radio buttons, as these obtain the value that corresponds to the selected option value.

You can use this template for that purpose:

'##allowempty##';
var sum = 0;
var total = 0;
var variables = [{variable_1}, {variable_2}, {variable_3}];
for (var i = 0; i < variables.length; i++) { 
    var value = variables[i]; 
    if (value != 'NA') {
       sum = sum + value;
       total = total + 1;
    };
};
(sum/total).toFixed(2); // returns the average in the format 0.00

Replace variable_1, variable_2 and variable_3 with your own variables.

This calculation is also explained in this similar example.


Choose files or drag and drop files
Was this article helpful?
Yes
No
  1. Tonya

  2. Posted
  3. Updated