Search Knowledge Base by Keyword

Variance Function

Last review: March 2024

Goal:

Calculate a variance from numbers inserted to Text Inputs in a Document or Bundled Documents.

Instructions:

  1. Create the Template tag Variance and attach this tag to all Text Inputs in your Template that should be calculated.
  2. Create the Template tag GetVarianceValue and attach this tag to the Text Input in your Template where the sum amount should be inserted.
  3. Insert the below-mentioned script to the Variance tag.

Script Example:

const Tags = LEGITO.documentBuilder.getTagsByName("Variance");

 

var finder = LEGITO.documentBuilder.event.createElementFinder();
var modeValues = finder.findElementsByTagsAuto(Tags);

 

const Results = LEGITO.documentBuilder.getTagsByName("GetVarianceValue");
var resultElement = finder.findElementsByTagsAuto(Results)[0];

 

let valuesArray = []
for(var i in modeValues) {
if(modeValues[i].getValue() !== null) {
valuesArray.push(parseInt(modeValues[i].getValue(), 10));
}
}

 

const getNumWithSetDec = function( num, numOfDec ){
    var pow10s = Math.pow( 10, numOfDec || 0 );
    return ( numOfDec ) ? Math.round( pow10s * num ) / pow10s : num;
};

 

const getAverageFromNumArr = function( numArr, numOfDec ){
    var i = numArr.length,
        sum = 0;
    while( i-- ){
        sum += numArr[ i ];
    }
    return getNumWithSetDec( (sum / numArr.length ), numOfDec );
};

 

const getVariance = function( numArr, numOfDec ){
    var avg = getAverageFromNumArr( numArr, numOfDec ),
        i = numArr.length,
        v = 0;
 
    while( i-- ){
        v += Math.pow( (numArr[ i ] - avg), 2 );
    }
    v /= numArr.length;
    return getNumWithSetDec( v, numOfDec );
};

 

resultElement.setValue(getVariance(valuesArray, 2).toString());