Arrays

An array is a data structure consisting of a collection of elements, each of which is identified by a specific position in the array, called an index. The size of the array can change as new elements are added, and existing elements removed.  Since array sizes are dynamic, a simple iterative statement (loop) is usually the best way to process some or all elements in the array. 

Snap blocks are available to manipulate arrays in the following ways:

  • Add / Remove elements
  • Empty the array (remove all elements at once)
  • Retrieve or remove an element at a given index
  • Get the index of an element with a specific value
  • Get the size of the array (number of elements)
  • Searching and Querying for elements which meet a specific criteria
  • Loop through each index
  • Perform aggregate functions on the contents of the array, such as Sum, Min, Max, and Average.


Regardless of how you process an array, keep these array concepts in mind:

  1. Zero-based counting.
    The index value of each element of the array is 0 based. Thus the first element has an index of 0 while an element at the nth position has an index of n-1.  A common mistake is skipping the first or last entry in an array.
  2. Dynamic size, but not dynamic structure.
    The number of elements (array size) may vary at run time. But the element type must remain the same. For example, if you have an array of numbers, you can add or remove numbers to the array, but you cannot add a string.
  3. Arrays can contain simple types or complex types.
    You can create an array from just about anything in KBMax – from a simple type (like a text array, or a number array), to complex custom types you define (see the examples below).
  4. Arrays are unidimensional.
    As you see in the examples below, you refer to an element in an array by specifying a simple position along one dimension.  If you want to create a two-dimensional array, just create an array of arrays.

Creating Arrays

Example 1: Creating an array of a simple type

In this example an array to hold the names of colors is declared. The array type is text. Three colors are then added: "Red", "Orange", and "Yellow". Then a loop is shown to process each element of the array.

Example 2: Creating an array of a complex type

Arrays can also be of a complex type.  First, define the type (in a global rule is the most scalable idea, but you can also define a type directly in your rule, as we do here). 

Then, create a few variables of that type. 

Finally, declare your array, and add those variables to it to build a complex array.


Examples: Searching and Querying Arrays

Snap includes blocks for searching and querying arrays: you can search an array through procedural programming commands, or query it like a table or database through statements containing complex logic. Depending on your needs and programming style, both techniques are useful ways to manage arrays.  Learn more.




Was this article helpful?