An array is an ordered list of values. Each value is called an element, and each element has a numeric position in the array, known as its index.

An element can be any type of data, eg. a string, a boolean, a number, or even an object or another array. An element can also be a dynamic value, eg. system.userInput. Each element can have a different type.

An array is contained within two square brackets: [], and its elements are separated by comas. For example, this array: ["one", 1] contains two elements: the string "one" and the number 1.

Arrays are commonly used to store, process and send data. In Automate, you may meet them while using NLU API, Knowledge Base, integrations with external databases etc.

In Automate, you can create, access, and modify arrays using Expression language (AEL) or JavaScript (JS).

Below, you will find a list of all operations and methods that can be performed on arrays.

πŸ“˜

Nested arrays

An array without any element that is an object or an array is called a one-dimensional array.

An array with elements that are objects and/or arrays is called a multi-dimensional or nested array.

πŸ‘

Using multiple methods at once

You can perform complex operations on arrays (and other data types) by joining methods together.

Each time you use any of the methods listed below, you get a result instantly. Then, you can use another method in the same line to be performed on this result, and so on...

For example, to skip the first three elements of an array and check the length of this new, shorter array, you could write such expression:

[1, 3, 5, 7, 9].skip(3).length()
Result: 2

πŸ‘‰ Learn more about using multiple methods in one expression

Full list of array methods

The following table contains a list of 3 essential array operations that are further explained below:

EssentialsDescription
Create an arrayInitialize an array using literal constructor, eg. ["one", "two"]. Learn more
Access an element by indexAccess a specific element using its index [i]. Learn more
For each loopIterate through an array's elements to join and print its elements. Learn more

The following table contains all methods used to process and modify arrays in Expression language. Click on a link for more information and examples:

MethodsDescriptionArgumentResult
add()Adds a new element to an existing array.any*array
concat()Creates a new array by joining two arrays into one.arrayarray
contains()Checks if an array contains given element.any*boolean
exists()Checks if an array contains an element that satisfies given conditions.functionboolean
filter()Creates a new array with elements that satisfy given conditions.functionarray
find()Returns the first element that satisfies given conditions.functionvarious*
first()Creates a new array from the first n elements of an array.numberarray
join()Creates a string by joining all elements of an array.stringstring
last()Creates a new array from the last n elements of an array.numberarray
length()Returns a number of elements of an array.-number
map()Creates a new array by applying a specified function to every element of an array.functionarray
skip()Creates a new array by excluding the first n elements from an array.numberarray
sort()Sorts an array of elements with compatible types in an ascending order.-array
sortDesc()Sorts an array of elements with compatible types in an descending order.-array
sortBy()Sorts an array of objects by a specified property in an ascending order.functionarray
sortByDesc()Sorts an array of objects by a specified property in an descending order.functionarray
sum()Returns a sum of the numbers stored in an array.array of numbersnumber
unique()Creates a new array containing unique values.-array

_any - any data type, eg. a string, a boolean, or an object. Learn more about data types.
_various - any data type. It is identical to the original element.

Create (initialize) an array

To create an array (e.g. when setting variable in memory), simply input wished array using square brackets and comas. In JS, it is called 'literal constructor'.

Examples:

// Create an array with  4 elements - 2 numbers and 2 strings:
[1, 2, "foo", "bar"]
// Create an empty array:
[]

// Tip: create an empty array so you can later add elements to it with add()
// Create an array with two elements that are variables stored in Memory:
[memory.firstStep, memory.secondStep]
// Create an array with two elements that are objects: 
[
  {
  firstName: "Michael",
  lastName: "Scott"
  },
  {
  firstName: "James",
  lastName: "Halpert",
  age: 34
  }
]

In Automate, you can initialize an array as a part of AEL expression, in any type of input field. Usually, you will see arrays that were created to be stored in Memory or Knowledge Base:

777

Create and store an array in Memory

672

Create and store an array in Knowledge Base

Access an element by index

Index is a number stating position of the element in an array.

To access an element by its index, add it directly after an array (or a variable storing an array - see Example 2), wrapped in square brackets.

πŸ“˜

[0] is the index of 1st element

Beware that in AEL and JS, the first element of an array has index 0.
That's why, to access the first element, use [0], to access the second one, use [1], etc.

🚧

Calling an index outside of array's length

If you try to call an index that is too high, an error will occur.

For example, if an array's length equals 3 (it has three elements), then you can call up to three indexes: [0], [1], or [2]. Calling [3] or anything higher on this array will result in an error.

To make sure that you won't call an index that is too high, check it's length().

Examples:

// Access the fourth element of an array:
[1, 2, "foo", "bar"][3]

// Result:
"bar"
// Access the first element of an array stored in memory.someArray:
memory.someArray[0]

// For memory.someArray = ["English", "Polish", "Italian"]
// the result is:
"English"
// Access an element of an array with an index stored in a variable:
[1, 2, "foo", "bar"][memory.someIndex]

// For memory.someIndex = 2
// the result is :
"foo"
// Access an element of an array which itself is an element of a nested (outer) array:
[1, 2, ["Jim", "Pam"], "Michael"][2][1]

// Result:
"Pam"

// Explanation:
// [2] is accessing the third element of a nested array returning ["Jim", "Pam"],
// and then [1] is accessing the second element of this inner array, returning "Pam".

For each loop

Foreach is used to iterate through an array, transform it's elements, combine them together and print as a string (with new line character as a delimiter).

  1. Start the epression with foreach keyword. It is followed by the variable's name of your choosing and the keyword in. You will use this selected name to access the current element in an array. For example, the start of the expression can look like that: foreach product in or foreach element in.

  2. Next, input an array that you want to iterate through (or a variable storing an array, eg. nlu.variablesList).

  3. Finally, compose an interpolated string in a new line and inside double quotation marks. Access and modify the current element of an array with the name you selected by interpolating (throwing in) an expression inside curly brackets.

Examples:

// Iterate through a one-dimensional array of numbers and multiply them by 2:
foreach element in [1, 2, 3]
"{element * 2}"

// Result:
2
4
6
// Iterate through multi-dimensional array (an array of objects)
// that stores loan products in memory.products to print a readable message:

// Expression:
foreach product in memory.products
"{product.type} no. {product.num}, remaining debt: $ {product.amount}"

// For memory.products:
[
    {
        type: "Student loan", amount: 10020, num: "SL324"
    },
    {
        type: "Quick loan", amount: 2450, num: "QL222"
    }
]

// Result: 
Student loan no. SL324, remainig debt: $ 10020
Quick loan no. QL222, remainig debt: $ 2450

If you don't want to print all elements, you can use first(), last() or skip() functions on an array, for example:

// Iterate through a one-dimensional array of numbers and multiply them by 2 
foreach element in [1, 2, 3].first(2)
"{element * 2}"

// Result:
2
4

add()

Adds one or more elements at the end of an array.

Element can be any type of data, including array and object. add() without any argument throws an error.

  • Syntax: array.add(new_elements)
  • Result: array

Examples:

// Add a new element to an array:
["Meredith", "Kevin"].add("Todd")

// Result:
["Meredith", "Kevin", "Todd"]
// Add multiple elements to an array
["Meredith", "Kevin"].add("Todd", "Ryan")

// Result:
["Meredith", "Kevin", "Todd", "Ryan"]
// The variable memory.accountants stores an array which is a list of accountants. The new one named Kevin was hired, 
// so we want to add him to our array.

// Initial value stored in memory.accountants:
["Oscar", "Angela"]

// Use add() on memory.accountants: 
memory.accountants.add("Kevin")

// New value stored in memory.accountants:
["Oscar", "Angela", "Kevin"]
// You can add any type of data as a new element, eg. another array:

["some string", 22, 24.4].add(["some other string", true, 14])

// Result: 
["some string", 22, 24.4, ["some other string", true, 14]]

concat()

Creates a new array by joining two arrays into one.

  • Syntax: array.concat(joined_array)
  • Result: array

Examples:

// Concatenate two arrays:
[1, 2, 3].concat(["five", "seven"])

// Result: 
[1, 2, 3, "five", "seven"]
// Each of the concatenated arrays can be stored as a variable in Memory, Knowledge Base,
// or be taken from API response (in this case, NLU API):
memory.arr1.concat(nlu.variablesList)

// For memory.arr1 equal to:
[
"some string",
2
]

// and nlu.variablesList equal to:
[
    {
        name: "bank_transfer",
        score: 0.9
    },
    {
        name: "help",
        score: 0.2
    }
]

// Result: 
[
    "some string",
    2,
    {
        "name": "bank_transfer",
        "score": 0.9
    },
    {
        "name": "help",
        "score": 0.2
    }
]

contains()

Checks if an argument is identical to at least one of the array's elements.

Just like the array's elements, an argument of contains() can be of any type (string, boolean, number, object etc.).

To return true, the argument and the element of an array have to be of the same type.
For example, [1, 2].contains("1") will return false.

  • Syntax: array.contains(element_to_check)
  • Result: boolean (true or false)
  • Similar methods: exists(), filter(), find()

Examples:

// Check if an array contains the number 4:
[2, 3, 4, 5].contains(4)

// The result:
true
// For:
memory.arr1 = ["4", "5", "11"]
memory.arr2 = [4, 5, 11]
nlu.variables.numeral.value = 4

// Check if the first array (memory.arr1) contains the number recognized by NLU:
memory.arr1.contains(nlu.variables.numeral.value)
// Result: 
false

// Check if the second array (memory.arr2) contains the number recognized by NLU:
memory.arr2.contains(nlu.variables.numeral.value)
// Result: 
true

exists()

Checks if an array contains an element that satisfies given conditions.

Unlike with contains(), here you can use arrow function to check any condition, not just the identicalness of an argument and array's elements.

This method is useful to check arrays of objects. It lets you check if the condition is fulfiled for a specific property of objects that are elements of an array (see example 2).

Examples:

// Check if an array contains an element that is larger than 5 (an element has to be a number, too):
[1, 2, 6].exists(el => el > 5)

// Result: 
true
// For memory.arr1:
[
  { 
    Answer: 1, 
    QuestionId: 2 
  },
  { 
    Answer: 3, 
    QuestionId: 5 
  }
]

// Check if an array stored in memory.arr1 contains an object that has a property Answer
// which value is equal to 1:
memory.arr1.exists(el => el.Answer = 1)

// Result: 
true
// Check if there is an element that after using replace() on it will return "I'm 14":
["5", "10", "14"].exists(el => "I'm ??".replace("??", el) = "I'm 14")

// Result:
true

filter()

Creates an array from the elements of an initial array that satisfy given conditions.

This method uses arrow functions that let you create both simple and complex conditions. You can also add a few conditions using AND and OR operators.

Examples:

// Filter an array so that the new array has only elements larger than 3:
[1, 2, 4, 6].filter(el => el > 3)

// Result: 
[4, 6]

find()

Returns the first element of an array that satisfies given conditions.

This method uses arrow functions that let you create both simple and complex conditions. You can also add a few conditions using AND and OR operators.

If an array doesn't contain any element that satisfies given conditions, the result will be null.

Examples:

[10, 20, 30].find(el => el >= 20)

// Result:
20
// This array contains two objects. Find the first element (object) that has a property Answer equal to 5:
[{Answer: 1, QuestionId:"asd"},{Answer:5, QuestionId:"casd"}].find(el => el.Answer = 5)

// Result:
{Answer:5, QuestionId:"casd"}

first()

Creates a new array that consists of the first n elements of an initial array.

If an argument (number of elements to get) is equal to or higher than the length of an initial array (number of all elements), then the new array will be identical to the initial one.

  • Syntax: array.first(number)
  • Result: array
  • Similar methods: last(), skip()

Examples:

[1, 2, "foo", "bar"].first(2)

// Result:
[1,2]

join()

Creates a string from all of the elements of an array.

The string is composed from the elements ordered accordingly to the initial array. Each element is separated by a delimiter defined in an argument (delimiter_string).

Elements of the type different from string will be parsed to string, so you can use this method with any array.

  • Syntax: array.join(delimiter_string)
  • Result: string
  • See also: For each loop

Examples:

[1, 2, "foo", "bar"].join(",")
1, 2, "foo", "bar"

last()

Creates a new array that consists of the last n elements of an initial array.

If an argument (number of elements to get) is equal to or higher than the length of an initial array (number of all elements), then the new array will be identical to the initial one.

  • Syntax: array.last(number)
  • Result: array
  • Similar methods: first(), skip()

Examples:

[1, 2, "foo", "bar"].last(2)

// Result:
["foo", "bar"]

length()

Returns the number of elements in an array. This number is called an array's 'length'.

  • Syntax: array.length()
  • Result: number

Examples:

[1, 2, "foo", "bar"].length()

// Result:
4

map()

Creates a new array by performing a provided function on each element of an initial array.

The new array will always have the same length as the initial one.

This method uses arrow functions.

  • Syntax: array.map(function)
  • Result: array

Examples:

🚧

'Only supported by' errors

Be careful: map() requires that the provided function can by performed on all of the array's elements.

For example, you can only perform math equations like multiplying if all of the array's elements are numbers. See example 4.

// Create a new array with elements multiplied by 2:
[3, 5, 23].map(el => el * 2)

//Result:
[
6,
10,
46
]
[{Answer:1,QuestionId:2}].map(el => el.Answer)

skip()

Creates a new array that skips the first n elements and consists of the rest of the elements of the initial array.

If an argument (number of elements to get) is equal to or higher than the length of an initial array (number of all elements), then the new array will empty.

  • Syntax: array.skip(number)
  • Result: array
  • Similar methods: first(), last()

Examples:

[1, 2, "foo", "bar"].skip(2)

// Result:
["foo","bar"]

sort()

Creates a new array with elements sorted in an ascending direction.

You can sort arrays that:

  • contain only numbers and strings representing numbers or
  • contain only dates or
  • contain only strings (they will be sorted alphabetically).

Examples:

[1,3,1,2].sort()

// Result:
[1,1,2,3]

sortDesc()

Creates a new array with elements sorted in a descending direction.

You can sort arrays that:

  • contain only numbers and strings representing numbers or
  • contain only dates or
  • contain only strings (they will be sorted alphabetically).

Examples:

[1,1,2,3].sortDesc()

// Result
[3,2,1,1]

sortBy()

Sorts an array of objects by one of their properties in an ascending order.

You can sort by property values that:

  • contain only numbers and strings representing numbers or
  • contain only dates or
  • contain only strings (they will be sorted alphabetically).

Examples:

[{Answer:3,QuestionId:"asd"},{Answer:1,QuestionId:"casd"}].sortBy(el => el.Answer)

// Result:
{
 "Answer" : 1,
 "QuestionId" : "casd"
},{
 "Answer" : 3,
 "QuestionId" : "asd"
}

sortByDesc()

Sorts an array of objects by one of their properties in a descending order.

You can sort by property values that:

  • contain only numbers and strings representing numbers or
  • contain only dates or
  • contain only strings (they will be sorted alphabetically).

Examples:

[{Answer: 1,QuestionId:"asd"},{Answer:5,QuestionId:"casd"}].sortByDesc(el => el.Answer)

// Result:
{
 "Answer" : 5,
 "QuestionId" : "casd"
},{
 "Answer" : 1,
 "QuestionId" : "asd"
}

sum()

Returns a sum of all of the array's elements. It only works if all of the elements are numbers.

  • Syntax: array.sum()
  • Result: number

Examples:

[1, 2].sum()

// Result:
3

unique()

Creates a new array with unique elements of the initial array. In other words, this method clears an array of duplicates.

To be treated as duplicates, two or more elements have to be equal and have the same type. For example, 1 (number) and "1" (string) will not be treated as duplicates.

[1,1,2,3,"foo","bar","foo", "2"].unique() 

// Result:
[
1,
2,
3,
"foo",
"bar",
"2"
]

Arrow functions

Arrow functions is a concept taken from JavaScript ES6 (learn more).

In Expression language, arrow functions are used in array methods to:

  • define a condition that every item of an array will be tested against (eg. in filter() method),
  • perform a function on every item of an array (eg. in map() method).

The name "arrow functions" is taken from an arrow => used to separate an argument from a function.

Arrow function perform an operation on every element of an array (iterate through an array) and return the results.

Every arrow function consists of:

  1. An argument's name defined by the user. From now on, this name will indicate an element of an array that is currently processed. This is why they are usually defined as el, elem or element. The name of the argument can be anything, though. It doesn't change the way in which a function works.
  2. An arrow =>.
  3. A function to be performed on every element of an array that uses the named argument (eg. el * 2).

Examples of an arrow function:

el => el * 2 or elem => elem * 2

This two arrow functions do the exact same thing.

This arrow function will take every element of an array and multiply it by 2. Such arrow function would be used as an argument of the map() method, eg. [1, 3, 4].map(el => el * 2). The result would be a new array: [2, 6, 8].

To use arrow function to define a condition, it has to return either true or false as its result.

For example, the arrow function below is used as an argument for filter() method:

[2, 14, 22, 17, 5, 8].filter( el => el > 10)

The result of the function el > 10 can be either true or false, so it is a correct way to create a condition. Every element of the array [2, 14, 22, 17, 5, 8] will be tested against it and the filter() method will create a new array containing only the elements that fulfilled the condition el > 10 (its result was true).

The result of the expression above is [14, 22, 17].


What’s Next