3 Replies Latest reply on Oct 1, 2015 9:16 AM by patrickm57169148

    Javascript to calculate the average of a column


      Someone had posted this javascript in a discussion a few years ago to calculate the average of a column.  It works but now I need it edited so that it will only average those fields where the valueis greater than zero.  (I have three columns in a form, with the third column being the product of columns 1 & 2, since I don't know how many rows a user may fill in I had to input the product formula in the third column for each row and since I did that the value in the third column for each row is initially shown as zero unless an entry is made and because of this the script below is calculating the average with the fields that have a zero and I want the script to skip those fields.)


      Can anyone help me as my programming skills leave much to be desired.  Thanks!



      Script from a previous discussion

      First, I would write this function without field references to make it more universal, and then I would make it a document level funcion so it could be used more than once in a PDF and easily brought into another PDF.


      function Avg() {
      // computer average of non-empty passed field names
      var sum = 0; // sum of fields
      var count = 0; // counter for non-blank fields
      for(i = 0; i < arguments.length; i++) {
      var iField = arguments[i]; // get the i element from passed arguments
      var fField = this.getField(arguments[i]).value;
      if(!(isNaN(fField)) ) {
      // field is a number
      if(fField.toString() != '') {
      // field is not null or blank
      sum += Number(fField); // add to sum
      count++; // increment count
      } // end not blank
      } // end number
      } // end loop through arguments
      if(count != 0) {
      // compute average if there is one or more items to average
      return sum / count; // return average
      } else {
      return '';
      } // end no average computed
      } // end Avg function



      Your custom calculation script then becomes:


      event.value = Avg('column.0', 'column.1', 'column.2', 'column.3', 'column.4', 'column.5', 'column.6', 'column.7');