This article describes how to perform looping using JavaScript arrays.
Requirements
Please note these steps require a Displayr license.
A JavaScript variable with Access all data rows ticked.
Method
By default, all JavaScript functions work for each respondent separately (i.e. the operations are done for each case in your file). For example, the JavaScript expression q3 + q4
creates a new variable which contains the sum of the two input variables for each observation.
A more powerful (but more complex) way of writing JavaScript treats each of the variables as an array, which contains all the responses for all cases in the file. To access this more powerful method, you will need to check the Access all data rows option in the object inspector when editing your JavaScript code.
Example 1
When this option is not selected, a new JavaScript variable containing the value of 1 for each record would be created with this expression:
1
When this option is checked, however, the following expression is required to return the row index:
var result = new Array();
for (var i = 0; i < N; i ++)
result[i] = i;
result
Note that:
- The first line creates a variable called result and assigns an empty array to it.
- N is a reserved variable containing the number of observations in the data set.
- A loop is being used to iterate through all the N values.
- The final line returns the array that will become the JavaScript variable.
Similarly, if adding two variables, q3 and q4, rather than write q3 + q4
we need to write:
var result = new Array();
for (var i = 0; i < N; i ++)
result[i] = q3[i] + q4[i];
result
Example 2
In this example, we have a data set that includes duplicate records. In order to identify these records, we need to work with a loop and array.
The below code identifies the first instance of a duplicate record:
var _ids = ID; var _filter = []; for (var i=0; i < _ids.length;i++) { _ids.indexOf(_ids[i]) < i ? _filter[i] = 1 : _filter[i] = 0; }; _filter
- In this code, we define our ID variable as _ids and create an empty array called _filter.
- We then loop through all the record numbers to populate our filter array with a 1 if the id number already exists in a previous iteration or a 0 if it does not.
We could instead find the last instance of a duplicate by updating line 4 as follows:
_ids.lastIndexOf(_ids[i]) > i ? _filter[i] = 1 : _filter[i] = 0;
Next
How to Use JavaScript in Displayr
How to Create a Custom Numeric JavaScript Variable
How to Create a Custom JavaScript Text Variable
How to Work with JavaScript Arrays and Loops
How to Work with Conditional JavaScript Formulas