I'm trying to write a function to compute an average of embedded data. I piped the fields in, parse them (they are numbers with decimals, so I can use parseInt). Then I need to check if any of the values are zero, so I filter it. I then want to average the data points that are left over.
Qualtrics.SurveyEngine.addOnload(function()
{
var a = "${e://Fields/a}"
var b = "${e://Fields/b}"
var c = "${e://Fields/c}"
var a= parseFloat(a)
var b= parseFloat(b)
var c= parseFloat(c)
var all_values;
var all_values= [a, b, c];
function isnonzero(value) {
return value != 0;
}
var filter_it;
var filter_it = all_values.filter(isnonzero);
function avg(filter_it){
var sum = 0;
for (var i = 0; i < filter_it.length; i++) {
sum += parseFloat(arr[i])
}
return average= sum / i;
}
Qualtrics.SurveyEngine.setEmbeddedData("total",average);
I don't think my function is right, or the way I tried to get the info out of the function. Any help would be awesome!
You have a couple of problems here, first, you don't need to re-initialize a variable after it has been defined. Second, you never call your avg() function. And third, you can't use the value of i outside of the for loop. YOu also never define arr in the avg() function. And you don't define average outside the avg function Try the following:
Qualtrics.SurveyEngine.addOnload(function()
{
var a = "${e://Fields/a}"
var b = "${e://Fields/b}"
var c = "${e://Fields/c}"
a= parseFloat(a)
b= parseFloat(b)
c= parseFloat(c)
var all_values= [a, b, c];
function isnonzero(value) {
return value != 0;
}
var filter_it;
filter_it = all_values.filter(isnonzero);
function avg(filter_it){
var sum = 0;
for (var i = 0; i < filter_it.length; i++) {
sum += parseFloat(filter_it[i])
}
return sum / filter_it.length;
}
var average = avg(filter_it);
Qualtrics.SurveyEngine.setEmbeddedData("total",average);
});