Value assignment functions

This page is an extension of the Value Assignment basic functionality, if you are not yet familiar using the value assingment, please read here.

Disclaimer: If you have a professional user license, you can use all functions described in this page. However, if you are stuck, you need an extended support contract (SLA) to get our assistance. Survalyzer product support does not include value assignments. Contact our sales team to get a extended support contract.

Math.js functions

As a foundation of the value assingment element we use math.js. There are out-of-the-box functions you can use. In case, the following listed functions do not fulfill your requirements, you may search for more in math.js function reference: https://mathjs.org/docs/reference/functions.html

Arithmetic

FunctionDescriptionExample CallExample Result
+adds termssum=3+25
subtracts termsdifference=3-21
*multiplies termsproduct=3*26
/divides termsquotient=3/21.5
%calculates the modulusmodulus=3%21
^exponentiates termssquare=3^29
sqrtcalculates the square rootresult=sqrt(9)3
abscalculates the absolute valueresult1=abs(-5)
result2=abs(5)
5
5
roundrounds number to decimalresult=round(2.35,1)2.4

Statistics

Download JSON of statistics reference survey and import it into your workspace.

FunctionDescriptionExample CallExample Result
sumcalculates the sumsum(2,3,5)10
meancalculates the meanmean(2,3,5)3.3333…
mediancalculates the medianmedian(2,3,5)3
stdcalculates the standard deviationstd(2,3,5)1.5275…
variancecalculates the variancevariance(2,3,5)2.3333…
mincalculates the minimum valuesmin(2,3,5)2
maxcalculates the maximum valuemax(2,3,5)5

Randomisation

Download JSON of randomisation reference survey and import it into your workspace.

FunctionDescriptionExample CallSurvey Reference
randomreturns a real number between min (included) and max (excluded)random(min,max)
randomIntreturns an integer number between min (included) and max (excluded)randomInt(min,max)Section 2 of randomisation survey
pickRandomreturns a randomly chosen element out of the given listpickRandom([var1,var2,var3])Section 1 of randomisation survey
shuffleshuffles the values of a matrixshuffle([var1,var2,var3])
shuffleChoicesWithinBlockrandomly sorts the answer options within specified blocksshuffleChoicesWithinBlock("q1",[1,2,3],[4],[5,6])
shuffleChoicesByBlockrandomly sorts the specified blocks of answer optionsshuffleChoicesByBlock("q1",[1,2,3],[4],[5,6])

Conditional instructions (if-then-else)

The basic syntax of a conditional instruction is:
IF condition ? THEN action : ELSE action
– the question mark and the colon are required
– only one THEN action and one ELSE action can be defined
– in case of no action use the word null
– the condition can contain logical operators and and or as well as brackets
– two or more conditional instructions can be nested (corresponds to ELSEIF)

ExampleDescriptionInputOutput
q1==1 ? var1=1 : nullif question variable q1 has the value 1 (e.g. first answer of single response question is chosen), then assign the value 1 to the custom variable var1 or elsewise do nothingq1=1
q1=2
var1=1
var1=var1
q2>1 ? var2=1 : var2=0if question variable q2 has a value bigger than 1, then assign the value 1 to custom variable var2 or elsewise assign the value 0 to custom variable var2q2=1
q2=2
q2=3
var2=0
var2=1
var2=1
age>=18 and age<=65 ? counter=counter+1 : nullif question variable age has a value between 18 and 65, then add 1 to the custom variable counter or elsewise do nothingage=15
age=45
age=75
counter=counter
counter=counter+1
counter=counter
(zip>=1000 and zip<=1007) or (zip>=1010 and zip<=1019) ? town="Lausanne" : nullif variable zip is between 1000 and 1007 or between 1010 and 1019, then assign “Lausanne” to variable town or elsewise do nothingzip=1008
zip=1018
zip=8005
town=town
town=”Lausanne”
town=town
equals(email1,email2)==true ? mailcheck=1 : mailcheck=0if both text entries from email1 and email2 are the same, then assign 1 to mailcheck or elsewise assign 0 to mailcheckemail1=”a@bc.de”
email2=”a@bc.de”

email1=”a@bc.de”
email2=”k@lm.no”
mailcheck=1


mailcheck=0
age<18 ? group=1 : age<30 ? group=2 : age<50 ? group=3 : age<=65 ? group=4 : group=5nested conditional instructions: if age<18 then group=1 elseif age<30 then group=2 elseif age<50 then group=3 elseif age<=65 then group=4 elsewise group=5age=5
age=25
age=45
age=65
age=85
group=1
group=2
group=3
group=4
group=5

Texts

Download JSON of texts reference survey and import it into your workspace.

FunctionDescriptionExample CallExample Result
concatconcatenates textsconcat("8005"," ","Zürich")“8005 Zürich”
equalscompares texts and returns either “true” or “false”equals("8005","Zürich")false
containscompares substring in texts and returns either “true” or “false”contains("or","World")true
countcounts the characters of a textcount("8005 Zürich")11
[start:stop]returns a substring, beginning at “start” and ending at “stop” (number of character)"8005 Zürich"[1:4]“8005”
indexOfreturns the start position of a search string (be aware: first character is 0)indexOf("8005 Zürich","Zürich")
indexOf("8005 Zürich","Utrecht")
5

-1
subsetreplaces characters at defined positionsubset("8000 Zurich",index(4:7),"5 Zü")“8005 Zürich”

Date & Time

Download JSON of data transformation reference survey and import it into your workspace.

FunctionDescriptionExample CallSurvey Reference
dateconverts a string (variable) to a date (variable)date("13/02/2024")
number2dateconverts a Unix timestamp to a datenumber2date(varTimestamp)
dateFormatformats a date (incl. time) as specified (data type string)dateFormat(varDate, "DD/MM/YYYY HH:mm:ss")
date2numberreturns the Unix timestamp (number of milliseconds) for a given datedate2number(varDate)Section 1 of data transformation survey
datetime2numberreturns the Unix timestamp (number of milliseconds) for a given time (incl. a date)datetime2number(varDateTime)
todayreturns current date and time (data type date)today()Section 1 of data transformation survey
addDaysadds number of days specified to a given date (data type date)addDays(today(),-7)
getRunTimeInSecreturns the number of seconds since the beginning of the interviewgetRunTimeInSec()

Data transformation

Download JSON of data transformation reference survey and import it into your workspace.

FunctionDescriptionExample CallSurvey Reference
parseNumberreturns integer number enclosed in textparseNumber(varText)Section 2 of data transformation survey
parseRealreturns real number enclosed in textparseReal(varText)
convertToStringconverts given number into textconvertToString(varNumber)Section 2 of data transformation survey
binreturns binary value of number (data type text)bin(varNumber)
hexreturns hexadecimal value of number (data type text)hex(varNumber)
toJSONconverts JSON string into JSON variabletoJSON(varText)

Counters

Download JSON of counters reference survey and import it into your workspace.

FunctionDescriptionExample CallSurvey Reference
count_startedcalculates the number of interviews with status “InProgress”survey.count_startedSection 2a of randomisation survey
count_completedcalculates the number of interviews with status “Completed”survey.count_completedSection 2a of randomisation survey
countInterviewscalculates the number of interviews that meet the custom conditioncountInterviews(customCondition)

example for a customCondition:
countInterviews(q1==1 and survey.State=='Completed')
Section 1 of counters survey
getCountQuestionreturns the number of questions in the whole surveygetCountQuestion()
getCountVariablereturns the number of variables in the whole surveygetCountVariable()

Array & Matrix

Download JSON of matrixto reference survey and import it into your workspace.

FunctionDescriptionExample CallExample Result
csvToNumberArrayconverts a CSV string into a number array (data type matrix)csvToNumberArray('34,34,123,43')[34,34,123,43]
csvToStringArrayconverts a CSV string into a string array (data type matrix)csvToStringArray('34, 34, 123 , 43')[“34″,”34″,”123″,”43”]
[dim1,dim2]returns the element of a matrix at position “dim1” and “dim2”varMatrix=[[1,2,3],[3,4,5],[5,6,7],[7,8,9]]
varMatrix[2,3]
5
matrixToFlatArrayreturns a one dimensional matrix (=array) out of a multi dimensional matrixvarMatrix=[[1,2,3],[3,4,5],[5,6,7],[7,8,9]]
matrixToFlatArray(varMatrix[1:end,2])
[2,4,6,8]
mapmaps each value of a matrix according to a defined custom functionvarMatrix=[2,4,6,8]
custom function that replaces 2 or 6 with 0:
myFunction(value)= value==2 or value==6 ? 0 : value
mapping after the custom function:
map(varMatrix,myFunction)
[0,4,0,8]
sortsorts an arrayvarMatrix=[0,4,0,8]
sort(varMatrix,'asc')
[0,0,4,8]
filterfilters an array according to a defined custom functionvarMatrix=[0,0,4,8]
custom function that filters null missings and zero values:
myFunction(value)= value!=null and value!=0
filtering after the custom function:
filter(varMatrix,myFunction)
[4,8]
countdetermines the number of elements in an arrayvarMatrix=[4,8]
count(varMatrix)
2
meancalculates the mean of the elements of an arrayvarMatrix=[4,8]
mean(varMatrix)
6
resizeresizes (reduces or extends) a matrix or an arrayvarMatrix=[4,8]
varMatrix.resize([1])
varMatrix.resize([5])
varMatrix.resize([5],2)

[4]
[4,8,0,0,0]
[4,8,2,2,2]
matrixToHtmlgenerates HTML table code from a matrix variable; output via placeholder in the survey is a tablematrixToHtml(varMatrix)
or with formatted header
matrixToHtml(varMatrix,{firstRowAsHeader:true})
dataSourceToMatrixgets the results from a datasource within a report and writes the results into a matrix variabledataSourceToMatrix(reportID,datasourceID)

Mapping, filtering and foreach loops with custom functions

Math.js features a function called map that creates a new array or matrix out of a given array or matrix based on a callback function. You can use this as a foreach loop as described below.
Read more about the map function on math.js documentation.
You may define any callback function you want – therefore, let us call them custom functions. Make sure the custom function is defined before you do the map function call.
Besides the map function also a filter function exists that basically uses the same logic. In contrast to the mapping the filtering keeps certain elements according to the custom function and removes the others.
Instead, if you want to use a loop that does not necessarily change the matrix or array used for the looping, you can work with the foreach function. You still need a matrix or an array to loop through all the elements, but you may create an auxiliary array with e.g. enumerated values first.

ExampleDescriptionInputOutput
myFunction(x) = x*x

myResult=map(myArray,myFunction)
the custom function myFunction squares each provided value; the map function hands over myArray to myFunction for creating the new array myResult with the squares for each element of myArraymyArray=[1,2,3]myResult=[1,4,9]
myFilter(x) = x!=null and x!=0

myResult=filter(myArray,myFilter)
the custom function myFilter checks for each provided value if it is not null and not 0; the filter function hands over myArray to myFilter for filtering out empty and 0 values and keeping all other values in the new myResult arraymyArray=[0,1,2,3,null]myResult=[1,2,3]
myFunction(x) = equals(q1,getFrom(x,'zip')) ? getFrom(x,'town') : null

myArray=matrixToFlatArray(ziptownlist)
myResult=map(myArray,myFunction)

nullFilter(x) = x!=null

myTown=filter(myResult,nullFilter)[1]
myFunction is a lookup function that loops through the ziptownlist (JSON converted to flat array) and compares all list values with the answer from q1; myResult keeps the matching value and myTown returns the only left element after using the nullFilterq1=”8000″

ziptownlist=[
{“zip”:”1000″, “town”:”Lausanne”},
{“zip”:”1200″, “town”:”Genève”},
{“zip”:”3000″, “town”:”Bern”},
{“zip”:”4000″, “town”:”Basel”},
{“zip”:”8000″, “town”:”Zürich”}]
myResult=[null,null,null,null,”Zürich”]

myTown=”Zürich”
auxiliaryArray=range(1,20)

myFunction(x) = sum=sum+x

sum=0
foreach(auxiliaryArray,myFunction)
auxiliaryArray is created to have 20 elements from 1 to 20; myFunction sums-up the numbers 1 to 20 by using a foreach loopsum=210

Survey element’s controls

Download JSON of controls reference survey and import it into your workspace.

FunctionDescriptionExample CallSurvey Reference
setSurveyFieldsReadOnlysets text fields or multiple choice checkboxes into read only modesetSurveyFieldsReadOnly([VariableName])
setSurveyFieldsEditablereverts the read only modesetSurveyFieldsEditable([VariableName])
setSectionOrdersets the display order of the next sectionssetSectionOrder(["Section C","Section A","Section B"])
hide (back button)hides the back buttonBackButton("hide")Section 2 of controls survey
hide (next button)hides the next button for a defined number of secondsNextButton("hide",5)Section 1 of controls survey
click (next button)automatically clicks the next button after a defined number of secondsNextButton("click",5)Section 1 of controls survey
hideandclick (next button)hides the next button for a defined number of seconds and then automatically clicks on itNextButton("hideandclick",5)Section 1 of controls survey

Special features

Download JSON of custom function and if-then-else reference survey and import it into your workspace.

FunctionDescriptionExample CallSurvey Reference
isNullOrUndefined
isNull
isUndefined
used in conditions to check if variable is null or undefinedisNullOrUndefined(varText)
isNull(varText)
isUndefined(varText)
custom function and if-then-else reference survey
list functionhides non-selected answers of a list in follow-up questionslist(choice) = answer(concat('brand_',choice.code)) == 1 ? true : false
setChoicesVisibility('bestbrand',list)
JSON of list function reference survey
getSurveyLinkgenerates a personal link for a certain surveylink=getSurveyLink(123)JSON of survey link reference survey
returnreturns the value of a certain variable as final result of the value assignmentreturn(var)
FunctionDescriptionExample CallExample Result
getFromreturns the content of a JSON variable (up to 2 nested dimensions); pay attention to the enumerationvarJson = [
{"id":"1","name":"one"},
{"id":"2","name":"two"}
]


getFrom(varJson,'[1]')
getFrom(varJson,'[1].name')
getFrom(varJson[1],'name')






{“id”:”2″,”name”:”two”}
two
one
Updated on April 12, 2024

Article Attachments

Was this article helpful?

Related Articles

Need Support?
Please login to your Survalyzer account and use the "Create Support Request" form.
Login to Survalyzer