‘For-Each’ Iteration

One of the most important tasks that a computer can do it repetition of tasks. That’s why iteration is such an important element of JSL code. In version 16 of JMP, new syntax was introduced to describe the way we iterate over elements of structures such as lists and matrices.

The new syntax of iteration is based on the for each function. The documentation for this function describes its use for iterating over elements of ‘containers’. A container is just an abstract name for something that contains a collection of items: most commonly lists, but also matrices and associative arrays.

Example 1.1 Traditional for-loop

Here is an example of the traditional use of a for-loop in JSL:


Example 1.2 Iterating through elements of a list using ‘for each’


Example 1.3 Iterating through elements of a data table column
Example 2.1 transforming elements using a traditional for-loop

In example 1.3 above the height measurements are in inches. Do people really still l use inches? Let’s convert to centimetres:

Example 2.2 transforming elements using ‘transform each’
Example 3.1 the iteration index associated with a for loop

The iteration index is explicit in a for-loop:

Example 3.2 using the index keyword

Notice that this is the identical syntax for the use of ‘for each’. The only difference is the name of the element is ‘index’. Index is a keyword that indicates you want the index of the item and not the item value. If you want both, see the next example.

Example 3.3 using element-index pairs
Example 4.1 working with associative arrays

For each can also be used to work with associative arrays:

Example 5.1 working with multiple lists

Sometimes we work with collections of lists to track multiple associated quantities. Here is an example:

Example 5.2 for each item in multiple lists
Example 5.3 misasligned lists

When referencing items across lists the presumption is that the lists are of equal length. Problems occur if that is not the case:


Example 5.4 using the count option to resolve differences across containers


Example 5.5 strict enforcement

Leave a Reply

Your email address will not be published. Required fields are marked *