Calculating average from categories

Answered

Comments

5 comments

  • Rainer Grabowski

    Hi Mario,

    this code should work:

    var rat = @All of Rating
    
    var ratSum = 0
    for(var i = 0; i < rat.length; i++){
    ratSum +=parseFloat(rat[i])/rat.length
    };
    ratSum
    

    The numbers in the categories are strings(text); parseFloat() changes them to numbers so that ratSum+= can add them all.
    .length counts how many category fields are related. If you devide the ratSum by the number of related categories you get the average value.

    Rainer
    rg@delos-consulting.com

    0
    Comment actions Permalink
  • Mario Galea

    thanks a lot Rainer, both for code and explanation =)

    0
    Comment actions Permalink
  • Scott Anderson

    I have a similar challenge but with all fields being in the same app.  

    I am trying to calculate the average of several individual category fields.  There are about 8 category fields with the category options of each field being "0,1,2,3".  I am trying to get the average of these various fields into a separate calculation field.  Thank you. 

    0
    Comment actions Permalink
  • Rainer Grabowski

    Hi Scott,

    if all fields always have a value that's simply: 

    (+(@field1) + +(@field2) + +(@field3) + ...)/8

    If a field can be empty, but you only want to get the average of fields with values: 

    var arrFields = [@field,@field2,@field3 ...,@field8];
    var sum = 0;
    var numberValues = 0
    for(var i = 0; i < arrFields.length; i++){
    if(arrFields[i] != null){
    numberValues++
    sum +=+(arrFields[i]);
    }};
    sum/numberValues

    If a field can be empty, but you want to get the average of all 8 fields : 

    var arrFields = [@field,@field2,@field3 ...,@field8];
    var sum = 0;
    for(var i = 0; i < arrFields.length; i++){
    sum += +(arrFields[i]);
    };
    sum/arrFields.length

    Rainer

    0
    Comment actions Permalink
  • Scott Anderson

    Excellent!  Thank you Rainer I will try it out.  Thank you!

    0
    Comment actions Permalink

Please sign in to leave a comment.

Powered by Zendesk