Search code examples
javascriptsurveyqualtrics

Qualtrics- using javascript to create array then perform calculations


I have a survey in Qualtrics, and I need to do some calculations based on the answers from a matrix table. I need to find the "switchpoint."

The answers array will look something like this:

[0 0 0 1 1 1 1 1 1 1]

So for the above array, the switchpoint is between the 3rd and 4th element.

I'm not sure what the best way is to do this, and I've been struggling to figure it out - any guidance is most appreciated.

Here's what I'm trying to do:
I created an embedded data variable in survey flow to output the selected answers.

Var block1= [‘${q://QID664/SelectedAnswerRecode/1}’],
‘${q://QID664/SelectedAnswerRecode/2}’],
[‘${q://QID664/SelectedAnswerRecode/3}’],
[‘${q://QID664/SelectedAnswerRecode/4}’],
[‘${q://QID664/SelectedAnswerRecode/5}’],
[‘${q://QID664/SelectedAnswerRecode/6}’],
[‘${q://QID664/SelectedAnswerRecode/7}’],
[‘${q://QID664/SelectedAnswerRecode/8}’],
[‘${q://QID664/SelectedAnswerRecode/9}’],
[‘${q://QID664/SelectedAnswerRecode/10}’];

Then, parse

integers- var block1= parseInt([block1])

});

Then, i need to check the array in 2 ways to make sure it's "valid":

  • check to see if values in block1 array are all equal to 1 or all equal to 0
  • check to see if there are more than 2 switchpoints
  • if either of these are true, then this block is invalid

Then, find switchpoint and set that to a value.


Solution

  • A couple of things. First, your array definition is wrong...only one set of brackets and no 'smartquotes'. Second, parseInt only operates on a single string. It should be:

    Var block1= [parseInt("${q://QID664/SelectedAnswerRecode/1}"),
    parseInt("${q://QID664/SelectedAnswerRecode/2}"),
    parseInt("${q://QID664/SelectedAnswerRecode/3}"),
    parseInt("${q://QID664/SelectedAnswerRecode/4}"),
    parseInt("${q://QID664/SelectedAnswerRecode/5}"),
    parseInt("${q://QID664/SelectedAnswerRecode/6}"),
    parseInt("${q://QID664/SelectedAnswerRecode/7}"),
    parseInt("${q://QID664/SelectedAnswerRecode/8}"),
    parseInt("${q://QID664/SelectedAnswerRecode/9}"),
    parseInt("${q://QID664/SelectedAnswerRecode/10}")];
    

    Now block1 is an array of integers. You can loop through it with a for statement:

    for(i=0;i<block1.length;i++) {
      //Do something with block1[i]
    }