These functions can be used when working with, and manipulating arrays of data.
| Function | Description |
|---|---|
array::add() | Adds an item to an array if it doesn’t exist |
array::all() | Checks whether all array values are truthy, or equal to a condition |
array::any() | Checks whether any array value is truthy, or equal to a condition |
array::at() | Returns value for X index, or in reverse for a negative index |
array::append() | Appends an item to the end of an array |
array::boolean_and() | Perform the AND bitwise operations on two arrays |
array::boolean_or() | Perform the OR bitwise operations on two arrays |
array::boolean_xor() | Perform the XOR bitwise operations on two arrays |
array::boolean_not() | Perform the NOT bitwise operations on an array |
array::combine() | Combines all values from two arrays together |
array::complement() | Returns the complement of two arrays |
array::clump() | Returns the original array split into multiple arrays of X size |
array::concat() | Returns the merged values from two arrays |
array::difference() | Returns the difference between two arrays |
array::distinct() | Returns the unique items in an array |
array::fill() | Fills an existing array of the same value |
array::filter() | Filters out values that do not match a pattern |
array::filter_index() | Returns the indexes of all occurrences of all matching X value |
array::find() | Returns the first matching value |
array::find_index() | Returns the index of the first occurrence of X value |
array::first() | Returns the first item in an array |
array::flatten() | Flattens multiple arrays into a single array |
array::fold() | Applies an operation on an initial value plus every element in the array, returning the final result. |
array::group() | Flattens and returns the unique items in an array |
array::insert() | Inserts an item at the end of an array, or in a specific position |
array::intersect() | Returns the values which intersect two arrays |
array::is_empty() | Checks if an array is empty |
array::join() | Returns concatenated value of an array with a string in between. |
array::last() | Returns the last item in an array |
array::len() | Returns the length of an array |
array::logical_and() | Performs the AND logical operations on two arrays |
array::logical_or() | Performs the OR logical operations on two arrays |
array::logical_xor() | Performs the XOR logical operations on two arrays |
array::map() | Applies an operation to every item in an array and passes it on |
array::max() | Returns the greatest item from an array |
array::matches() | Returns an array of booleans indicating which elements of the input array contain a specified value. |
array::min() | Returns the least item from an array |
array::pop() | Returns the last item from an array |
array::prepend() | Prepends an item to the beginning of an array |
array::push() | Appends an item to the end of an array |
array::range() | Creates a number array from a range (start to end) |
array::reduce() | Applies an operation on every element in the array, returning the final result. |
array::remove() | Removes an item at a specific position from an array |
array::repeat() | Creates an array a given size with a specified value used for each element. |
array::reverse() | Reverses the sorting order of an array |
array::sequence() | Creates an array of sequential integers |
array::shuffle() | Randomly shuffles the contents of an array |
array::slice() | Returns a slice of an array |
array::sort() | Sorts the values in an array in ascending or descending order |
array::sort_lexical() | Sorts the values in an array, with strings sorted lexically |
array::sort_natural() | Sorts the values in an array, with numeric strings sorted numerically |
array::sort_natural_lexical() | Sorts the values in an array, applying both natural numeric and lexical ordering to strings |
array::sort::asc() | Sorts the values in an array in ascending order |
array::sort::desc() | Sorts the values in an array in descending order |
array::swap() | Swaps two items in an array |
array::transpose() | Performs 2d array transposition on arrays |
array::union() | Returns the unique merged values from two arrays |
array::windows() | Returns a number of arrays of length size created by moving one index at a time down the original array |
array::addThe array::add function adds an item to an array only if it doesn’t exist.
API DEFINITIONarray::add(array, value) -> array
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::add(["one", "two"], "three"); ["one", "two", "three"]
array::allWhen called on an array without any extra arguments, the array::all function checks whether all array values are truthy.
API DEFINITIONarray::all(array) -> bool array::all(array, value) -> bool array::all(array, @closure) -> bool
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::all([ 1, 2, 3, NONE, 'SurrealDB', 5 ]); -- false RETURN ["all", "clear"].all(); -- true
The array::all function can also be followed with a value or a closure to check if all elements conform to a condition.
RETURN ["same", "same", "same"].all("same"); -- true [ "What's", "it", "got", "in", "its", "pocketses??" ].all(|$s| $s.len() > 1); -- true [1, 2, "SurrealDB"].all(|$var| $var.is_string()); -- false
The array::all function can also be called using its alias array::every.
[1, 2, 3].every(|$num| $num > 0); -- true
array::anyThe array::any function checks whether any array values are truthy.
API DEFINITIONarray::any(array) -> bool array::any(array, value) -> bool array::any(array, @closure) -> bool
When called on an array without any extra arguments, the array::any function checks whether any array values are truthy.
RETURN array::any([ 1, 2, 3, NONE, 'SurrealDB', 5 ]); -- true ["", 0, NONE, NULL, [], {}].any(); -- false
The array::any function can also be followed with a value or a closure to check if any elements conform to a condition.
RETURN ["same", "same?", "Dude, same!"].any("same"); -- true [ "What's", "it", "got", "in", "its", "pocketses??" ].any(|$s| $s.len() > 15); -- false [1, 2, "SurrealDB"].any(|$var| $var.is_string()); -- true
The array::any function can also be called using the aliases array::some and array::includes.
[1, 2, 3].some(|$num| $num > 2); -- true [1999, 2001, 2002].includes(2000); -- false
array::atThe array::at function returns the value at the specified index, or in reverse for a negative index.
API DEFINITIONarray::at(array, index: int) -> any
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::at(['s', 'u', 'r', 'r', 'e', 'a', 'l'], 2); "r"
You can also pass a negative index. This will perform the lookup in reverse:
RETURN array::at(['s', 'u', 'r', 'r', 'e', 'a', 'l'], -3); "e"
array::appendThe array::append function appends a value to the end of an array.
API DEFINITIONarray::append(array, value) -> array
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::append([1, 2, 3, 4], 5); [ 1, 2, 3, 4, 5 ]
array::boolean_andThe array::boolean_and function performs the AND bitwise operations on the input arrays per-element based on the element’s truthiness. If one array is shorter than the other it is considered null and thus false.
API DEFINITIONarray::boolean_and(lh: array, rh: array)
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::boolean_and(["true", "false", 1, 1], ["true", "true", 0, "true"]); [true, true, false, true]
For those that take two arrays, missing elements (if one array is shorter than the other) are considered null and thus false.
RETURN array::boolean_and([true, true], [false]) [ false, false ]
array::boolean_orThe array::boolean_or function performs the OR bitwise operations on the input arrays per-element based on the element’s truthiness. It takes two arrays and if one array is shorter than the other or missing, the output is considered null and thus false.
API DEFINITIONarray::boolean_or(lh: array, rh: array)
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::boolean_or([false, true, false, true], [false, false, true, true]) [ false, true, true, true ]
array::boolean_xorThe array::boolean_xor function performs the XOR bitwise operations.
API DEFINITIONarray::boolean_xor(lh: array, rh: array)
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::boolean_xor([false, true, false, true], [false, false, true, true]); [ false, true, true, false ]
array::boolean_notThe array::boolean_not function performs the NOT bitwise operations on the input array(s) per-element based on the element’s truthiness. It takes in one array and it returns false if its single operand can be converted to true.
API DEFINITIONarray::boolean_not(array)
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::boolean_not([ false, true, 0, 1 ]); [ true, false, true, false ]
array::combineThe array::combine function combines all values from two arrays together, returning an array of arrays.
API DEFINITIONarray::combine(array, array) -> array
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::combine([1, 2], [2, 3]); [ [1, 2], [1, 3], [2, 2], [2, 3] ]
array::complementThe array::complement function returns the complement of two arrays, returning a single array containing items which are not in the second array.
API DEFINITIONarray::complement(array, array) -> array
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::complement([1, 2, 3, 4], [3, 4, 5, 6]); [ 1, 2 ]
array::concatThe array::concat function merges two arrays together, returning an array which may contain duplicate values. If you want to remove duplicate values from the resulting array, then use the array::union() function or cast it to a set using <set>.
API DEFINITIONarray::concat(array, array) -> array
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::concat([1, 2, 3, 4], [3, 4, 5, 6]); [ 1, 2, 3, 4, 3, 4, 5, 6 ]
As of SurrealDB 3.0.0-alpha.3, the behaviour of this function can also be achieved using the + operator.
RETURN [1, 2, 3, 4] + [3, 4, 5, 6]; [ 1, 2, 3, 4, 3, 4, 5, 6 ]
array::clumpThe array::clump function returns the original array split into sub-arrays of size. The last sub-array may have a length less than the length of size if size does not divide equally into the original array.
API DEFINITIONarray::clump(array, size: int) -> array
The following examples show this function, and its output, when used in a RETURN statement:
LET $array = [1, 2, 3, 4]; RETURN array::clump($array, 2); RETURN array::clump($array, 3);
Response[ [ 1, 2], [3, 4] ] [ [1, 2, 3], [4] ]
array::differenceThe array::difference function determines the difference between two arrays, returning a single array containing items which are not in both arrays.
API DEFINITIONarray::difference(array, array) -> array
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::difference([1, 2, 3, 4], [3, 4, 5, 6]); [ 1, 2, 5, 6 ]
array::distinctThe array::distinct function calculates the unique values in an array, returning a single array.
API DEFINITIONarray::distinct(array) -> array
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::distinct([ 1, 2, 1, 3, 3, 4 ]); [ 1, 2, 3, 4 ]
array::fillAvailable since: v2.0.0
The array::fill function replaces all values of an array with a new value.
API DEFINITIONarray::fill(array, any) -> array
The function also accepts a third and a fourth parameter which allows you to replace only a portion of the source array.
API DEFINITIONarray::fill(array, any, start: int, end: int) -> array
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::fill([ 1, 2, 3, 4, 5 ], 10); [ 10, 10, 10, 10, 10 ]
The following example shows how you can use this function with a starting position, and an ending position, which in this example will replace one item from the array:
RETURN array::fill([ 1, NONE, 3, 4, 5 ], 10, 1, 2); [ 1, 10, 3, 4, 5 ]
The following example shows how you can use this function with starting and ending negative positions, which in this example will replace one item from the array:
RETURN array::fill([ 1, 2, NONE, 4, 5 ], 10, -3, -2); [ 1, 2, 10, 4, 5 ]
array::filterThe array::filter function filters out values in an array that do not match a pattern, returning only the ones that do match.
API DEFINITIONarray::filter(array, value) -> array array::filter(array, @closure) -> array
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::filter([ 1, 2, 1, 3, 3, 4 ], 1); -- [ 1, 1 ] RETURN [true, false, false, false, true, true].filter(true); -- [ true, true, true ]
The array::filter function can also take a closure for more customized filtering.
[ { importance: 10, message: "I need some help with this query..." }, { importance: 0, message: "TEST Is this thing on?" }, { importance: 5, message: "I have an idea. What if we..."}, { importance: 100, message: "Stuck on an island with two hours of battery life left. Can you..."} ].filter(|$v| $v.importance > 5);
Response[ { importance: 10, message: 'I need some help with this query...' }, { importance: 100, message: 'Stuck on an island with two hours of battery life left. Can you...' } ]
Note that the function checks whether the output of the inner closure is truthy, as opposed to only expecting a bool. As any and all values can be checked for truthiness, simply passing the closure argument as its output is enough to filter out values that are not truthy, such as NONE values and empty arrays.
[1,2,3,NONE,0,"",{},[]].filter(|$v| $v);
Response[1,2,3]
A more real-life example of this pattern in which only the person records that have been seen by another are returned:
CREATE person:one, person:two; RELATE person:one->sees->person:two; (SELECT id, <-sees<-person AS is_seen_by FROM person) .filter(|$person| $person.is_seen_by);
Response[ { id: person:two, is_seen_by: [ person:one ] } ]
array::filter_indexThe array::filter_index function returns the indexes of all occurrences of all matching values.
API DEFINITIONarray::filter_index(array, value) -> array array::filter_index(array, @closure) -> array
The following examples show this function, and its output, when used in a RETURN statement:
RETURN array::filter_index(['a', 'b', 'c', 'b', 'a'], 'b'); -- [ 1, 3 ] RETURN [0, 0, 1, 0, 0, 5, 1].filter_index(0); -- [ 0, 1, 3, 4 ]
The array::filter_index function can also take a closure for more customized filtering.
[ { importance: 10, message: "I need some help with this query..." }, { importance: 0, message: "TEST Is this thing on?" }, { importance: 5, message: "I have an idea. What if we..."}, { importance: 100, message: "Stuck on an island with two hours of battery life left. Can you..."} ].filter_index(|$v| $v.importance > 5);
Response[0, 3 ]
array::findThe array::find function returns the first occurrence of value in the array or NONE if array does not contain value.
API DEFINITIONarray::find(array, value) -> value | NONE array::find(array, @closure) -> value | NONE
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::find(['a', 'b', 'c', 'b', 'a'], 'b'); -- b RETURN [1, 2, 3].find(4); -- [NONE]
The array::find function is most useful when a closure is passed in which allows for customized searching.
-- Find a number 3 or greater RETURN [1, 2, 3].find(|$num| $num > 3); -- Find the first adventurer good enough for the task [ { strength: 15, intelligence: 6, name: "Dom the Magnificent" }, { strength: 10, intelligence: 15, name: "Mardine" }, { strength: 20, intelligence: 3, name: "Gub gub" }, { strength: 10, intelligence: 18, name: "Lumin695" } ].find(|$c| $c.strength > 9 AND $c.intelligence > 9);
Response-------- Query -------- NONE -------- Query -------- { intelligence: 15, name: 'Mardine', strength: 10 }
array::find_indexThe array::find_index function returns the index of the first occurrence of value in the array or NONE if array does not contain value.
API DEFINITIONarray::find_index(array, value) -> number | NONE array::find_index(array, @closure) -> number | NONE
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::find_index(['a', 'b', 'c', 'b', 'a'], 'b'); -- 1 RETURN [1, 2, 3].find_index(4); -- NONE
The array::find_index function can also take a closure for more customized searching.
RETURN [1, 2, 3].find_index(|$num| $num > 3); -- NONE
The array::find_index function also be called using the alias array::index_of.
["cat", "badger", "dog", "octopus"].index_of("octopus"); -- 3
array::firstThe array::first function returns the first value from an array.
API DEFINITIONarray::first(array) -> any
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::first([ 's', 'u', 'r', 'r', 'e', 'a', 'l' ]); "s"
array::flattenThe array::flatten function flattens an array of arrays, returning a new array with all sub-array elements concatenated into it.
API DEFINITIONarray::flatten(array) -> array
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::flatten([ [1, 2], [3, 4], 'SurrealDB', [5, 6, [7, 8]] ]);
Response[ 1, 2, 3, 4, 'SurrealDB', 5, 6, [7, 8] ]
array::foldAvailable since: v2.1.0
The array::fold function returns a final value from the elements of an array by allowing an operation to be performed at each step of the way as each subsequent item in the array is encountered. To use array::fold, pass in an initial value, followed by parameter names for the current value and the next value and an operation to perform on them. If you only want to perform an operation on each item and do not need an initial value, use the array::reduce function instead.
API DEFINITIONarray::fold(array, initial_value, @closure) -> value
This function is commonly used to sum or subtract the items in an array from an initial value.
-- Returns 53 [10,12,10,15].fold(100, |$a, $b| $a - $b);
The function will then perform the following operation for each step of the way.
$a = 100 (initial value), $b = 10 (first item in the array). Operation $a - $b = 90. 90 is passed on.$a = 90, $b = 12. Operation $a - $b = 78. 78 is passed on.$a = 84, $b = 10. Operation $a - $b = 74. 68 is passed on.$a = 74, $b = 15. Operation $a - $b = 53. No more items to operate on in the array, 53 is returned.Another example showing array::fold() used to reverse a string:
"I am a forwards string" .split('') .fold("", |$one, $two| $two + $one);
Output'gnirts sdrawrof a ma I'
Or to modify a string in some other way.
"I don't like whitespace" .split(" ") .fold("", |$one, $two| $one + "_" + $two);
Output"_I_don't_like_whitespace"
As the output above shows, it is often nice to know which item of the array one is working with. This function allows a third parameter to be passed in that keeps track of the index of the current item.
"I don't like whitespace" .split(" ") .fold("", |$one, $two, $index| IF $index = 0 { $one + $two } ELSE { $one + "_" + $two });
Output"I_don't_like_whitespace"
The array::fold() function can be used to generate an array of values that can then be passed on to statements like INSERT for bulk insertion.
INSERT INTO person ( -- Create 1000 objects with a random ULID and incrementing number (<array>0..1000).fold([], |$v, $_, $i| { $v.append( { id: rand::ulid(), person_num: $i }); }) );
This function is also useful for aggregating the results of graph queries. The following shows a graph table called to that holds the distance from one city to another. The array::fold() function can then be used to pass an object along that tracks the first and last city, while accumulating the distance and number of trips along the way.
CREATE city:one, city:two, city:three; RELATE city:one -> to -> city:two SET distance = 25.5; RELATE city:two -> to -> city:three SET distance = 4.1; [ city:one, city:two, city:three ].map(|$v| { { city: $v, distance: 0, from: NONE, to: NONE, trips: 0 } }).fold({ city: NONE, distance: 0, from: NONE, to: NONE, trips: 0 }, |$acc, $val, $i| { RETURN IF $i = 0 { { city: $val.city, distance: 0, from: $val.city, to: NONE, trips: $acc.trips + 1 } } ELSE { { city: $val.city, distance: (SELECT VALUE distance FROM ONLY to WHERE in = $acc.city AND out = $val.city LIMIT 1) + $acc.distance, from: $acc.from, to: $val.city, trips: $acc.trips + 1 } }; }).chain(|$v| { { distance: $v.distance, from: $v.from, to: $v.to, trips: $v.trips } });
Final result:
{ distance: 29.6f, from: city:one, to: city:three, trips: 3 }
array::groupThe array::group function flattens and returns the unique items in an array.
API DEFINITIONarray::group(array) -> array
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::group([1, 2, 3, 4, [3, 5, 6], [2, 4, 5, 6], 7, 8, 8, 9]); [ 1, 2, 3, 4, 5, 6, 7, 8, 9 ]
array::insertThe array::insert function inserts a value into an array at a specific position. A negative index can be provided to specify a position relative to the end of the array.
API DEFINITIONarray::insert(array, value, number) -> array
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::insert([1, 2, 3, 4], 5, 2); [ 1, 2, 5, 3, 4 ]
array::intersectThe array::intersect function calculates the values which intersect two arrays, returning a single array containing the values which are in both arrays.
API DEFINITIONarray::intersect(array, array) -> array
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::intersect([1, 2, 3, 4], [3, 4, 5, 6]); [ 3, 4 ]
array::is_emptyAvailable since: v2.0.0
The array::is_empty function checks whether the array contains values.
API DEFINITIONarray::is_empty(array) -> bool
The following example shows this function, and its output, when used in a RETURN statement:
An array that contain valuesRETURN array::is_empty([1, 2, 3, 4]); false
An empty arrayRETURN array::is_empty([]); true
array::joinThe array::join function takes an array and a string as parameters and returns a concatenated string.
API DEFINITIONarray::join(array, string) -> string
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::join(["again", "again", "again"], " and "); "again and again and again"
array::lastThe array::last function returns the last value from an array.
API DEFINITIONarray::last(array) -> any
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::last([ 's', 'u', 'r', 'r', 'e', 'a', 'l' ]); "l"
array::lenThe array::len function calculates the length of an array, returning a number. This function includes all items when counting the number of items in the array. If you want to only count truthy values, then use the count() function.
API DEFINITIONarray::len(array) -> number
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::len([ 1, 2, 1, null, "something", 3, 3, 4, 0 ]); 9
array::logical_andThe array::logical_and function performs the AND logical operation element-wise between two arrays. The resulting array will have a length of the longer of the two input arrays, where each element is the result of the logical AND operation performed between an element from the left hand side array and an element from the right hand side array.
When both of the compared elements are truthy, the resulting element will have the type and value of one of the two truthy values, prioritizing the value and type of the element from the left hand side (the first array).
When one or both of the compared elements are not truthy, the resulting element will have the type and value of one of the non-truthy value(s), prioritizing the value and type of the element from the left hand side (the first array).
API DEFINITIONarray::logical_and(lh: array, rh: array)
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::logical_and([true, false, true, false], [true, true, false, false]); [ true, false, false, false ]
For those that take two arrays, missing elements (if one array is shorter than the other) are considered null and thus false
RETURN array::logical_and([0, 1], []) [ 0, null ]
array::logical_orThe array::logical_or function performs the OR logical operations element-wise between two arrays.
The resulting array will have a length of the longer of the two input arrays, where each element is the result of the logical OR operation performed between an element from the left hand side array and an element from the right hand side array.
When one or both of the compared elements are truthy, the resulting element will have the type and value of one of the two truthy value(s), prioritizing the value and type of the element from the left hand side (the first array).
When both of the compared elements are not truthy, the resulting element will have the type and value of one of the non-truthy values, prioritizing the value and type of the element from the left hand side (the first array).
API DEFINITIONarray::logical_or(lh: array, rh: array)
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::logical_or([true, false, true, false], [true, true, false, false]); [ true, true, true, false ]
If one of the array is empty, the first array is returned.
RETURN array::logical_or([0, 1], []); [ 0, 1 ]
array::logical_xorThe array::logical_xor function performs the XOR logical operations element-wise between two arrays.
The resulting array will have a length of the longer of the two input arrays, where each element is the result of the logical XOR operation performed between an element from the left hand side array and an element from the right hand side array.
When exactly one of the compared elements is truthy, the resulting element will have the type and value of the truthy value.
When both of the compared elements are truthy, the resulting element will be the bool value false.
When neither of the compared elements are truthy, the resulting element will have the type and value of one of the non-truthy values, prioritizing the value and type of the element from the left hand side (the first array).
API DEFINITIONarray::logical_xor(lh: array, rh: array)
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::logical_xor([true, false, true, false], [true, true, false, false]); [ false, true, true, false ]
If one of the array is empty, the first array is returned.
RETURN array::logical_xor([0, 1], []) [ 0, 1 ]
array::mapThe array::map function allows the user to call an anonymous function (closure) that is performed on every item in the array before passing it on.
API DEFINITIONarray::map(array, @closure) -> array;
The most basic use of array::map involves choosing a parameter name for each item in the array and a desired output. The following example gives each item the parameter name $v, which can then be used to double the value.
[1, 2, 3].map(|$v| $v * 2);
Response[ 2, 4, 6 ]
An example of a longer operation that uses {} to allow the closure to take multiple lines of code:
["1", "2", "3"].map(|$val| { LET $num = <number>$val; LET $is_even = IF $num % 2 = 0 { true } ELSE { false }; { value: $num, is_even: $is_even } });
Response[ { is_even: false, value: 1 }, { is_even: true, value: 2 }, { is_even: false, value: 3 } ]
The types for the closure arguments and output can be annotated for extra type safety. Take the following simple closure:
[1, 2, 3].map(|$num| $num + 1.1);
The output is [2.1f, 3.1f, 4.1f].
However, if the 1.1 inside the function was actually a typo and should have been the integer 11, the following would have prevented it from running.
[1, 2, 3].map(|$num: int| -> int { $num + 1.1 });
Response'There was a problem running the ANONYMOUS function. Expected this function to return a value of type int, but found 2.1f'
The array::map function also allows access to the index of each item if a second parameter is added.
[ ": first used in the year 876", ": the number of moons in the sky", ": also called a pair" ] .map(|$item, $index| <string>$index + $item);
Response[ '0: first used in the year 876', '1: the number of moons in the sky', '2: also called a pair' ]
The array::map() function can be used to generate an array of values that can then be passed on to statements like INSERT for bulk insertion.
-- Create 1000 objects with a random ULID INSERT INTO person ((<array>0..=1000).map(|| {id: rand::ulid()}));
For a similar function that allows using a closure on entire values instead of each item in an array, see the chain method.
array::maxThe array::max function returns the greatest value from an array of values.
API DEFINITIONarray::max(array<any>) -> any
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::max([0, 1, 2]); 2
As any value can be compared with another value, the array can be an array of any SurrealQL value.
array::max([NONE, NULL, 9, 9.9]); 9.9f
See also:
math::max, which extracts the greatest number from an array of numberstime::max, which extracts the greatest datetime from an array of datetimesarray::matchesThe array::matches function returns an array of booleans indicating which elements of the input array contain a specified value.
API DEFINITIONarray::matches(array, value) -> array<bool>
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::matches([0, 1, 2], 1); [false, true, false]
The following example shows this function when the array contains objects.
RETURN array::matches([{id: r"ohno:0"}, {id: r"ohno:1"}], {id: r"ohno:1"}); [ false, true ]
array::minThe array::min function returns the least value from an array of values.
API DEFINITIONarray::min(array<any>) -> any
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::min([0, 1, 2]); 0
As any value can be compared with another value, the array can be an array of any SurrealQL value.
array::min([NONE, NULL, 9, 9.9]); NONE
See also:
math::min, which extracts the least number from an array of numberstime::min, which extracts the least datetime from an array of datetimesarray::popThe array::pop function removes a value from the end of an array and returns it. If the array is empty, NONE is returned.
API DEFINITIONarray::pop(array) -> value
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::pop([ 1, 2, 3, 4 ]); 4
array::prependThe array::prepend function prepends a value to the beginning of an array.
API DEFINITIONarray::prepend(array, value) -> array
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::prepend([1, 2, 3, 4], 5); [ 5, 1, 2, 3, 4 ]
array::pushThe array::push function prepends a value to the end of an array.
API DEFINITIONarray::push(array, value) -> array
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::push([1, 2, 3, 4], 5); [ 1, 2, 3, 4, 5 ]
array::rangeAvailable since: v2.0.0
The array::range function creates an array of numbers from a given range.
API DEFINITIONarray::range(start: int, count: int) -> array -- Also since 3.0.0-alpha.8 array::slice(array, range) -> array;
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::range(1, 10); [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
RETURN array::range(1..=5); [ 1, 2, 3, 4, 5 ]
array::reduceAvailable since: v2.1.0
The array::reduce function reduces the elements of an array to a single final value by allowing an operation to be performed at each step of the way as each subsequent item in the array is encountered. To use array::reduce, pass in parameter names for the current value and the next value and an operation to perform on them. If you need an initial value to pass in before the other items are operated on, use the array::fold function instead.
API DEFINITIONarray::reduce(array, @closure) -> value
This function is commonly used to sum or perform some other mathematical operation on the items in an array.
[10,20,30,40].reduce(|$a, $b| $a + $b);
The function will then perform the following operation for each step of the way.
$a = 10, $b = 20. Operation $a + $b = 30. 30 is passed on.$a = 30, $b = 30. Operation $a + $b = 60. 60 is passed on.$a = 60, $b = 40. Operation $a + $b = 100. No more items to operate on in the array, 100 is returned.Another example showing array::reduce() used to reverse a string:
"I am a forwards string" .split('') .reduce(|$one, $two| $two + $one);
Output'gnirts sdrawrof a ma I'
Or to modify a string in some other way.
"I don't like whitespace" .split(" ") .reduce(|$one, $two| $one + "_" + $two);
Output"I_don't_like_whitespace"
It is often nice to know which item of the array one is working with. The following example shows a reduce operation performed on an array, but only up to index 2. For any further indexes, the value is simply passed on.
[ { name: "Daughter", money: 100 }, { name: "Father", money: 1000 }, { name: "Grandfather", money: 550 }, { name: "Great-grandmother", money: 10000 } ].reduce(|$one, $two, $index| IF $index > 2 { $one } ELSE { { name: $one.name + " and " + $two.name, money: $one.money + $two.money } });
Output{ money: 1650, name: 'Daughter and Father and Grandfather' }
array::removeThe array::remove function removes an item from a specific position in an array. A negative index can be provided to specify a position relative to the end of the array.
API DEFINITIONarray::remove(array, number) -> array
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::remove([1, 2, 3, 4, 5], 2); [ 1, 2, 4, 5 ]
The following examples shows this function using a negative index.
RETURN array::remove([1, 2, 3, 4, 5], -2); [ 1, 2, 3, 5 ]
array::repeatAvailable since: v2.0.0
The array::repeat function creates an array of a given size contain the specified value for each element.
API DEFINITIONarray::repeat(any, count: int) -> array
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::repeat(1, 10); [ 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 ]
RETURN array::repeat("hello", 2); [ "hello", "hello" ]
array::reverseThe array::reverse function reverses the sorting order of an array.
API DEFINITIONarray::reverse(array) -> array
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::reverse([ 1, 2, 3, 4, 5 ]); [ 5, 4, 3, 2, 1 ]
array::sequenceAvailable since: v3.0.0-alpha.11
The array::sequence function creates an array of sequential integers.
API DEFINITIONarray::shuffle(length: int) -> array array::shuffle(start: int, length: int) -> array
A single number passed in as an argument will create an array beginning at 0 with a length of the number indicated.
array::sequence(5); -- [0, 1, 2, 3, 4]
If a second argument is passed into this function, the first argument will be used as the starting point for the array and the second for the length.
array::sequence(-5, 6); -- [-5, -4, -3, -2, -1, 0]
array::shuffleAvailable since: v2.0.0
The array::shuffle function randomly shuffles the items of an array.
API DEFINITIONarray::shuffle(array) -> array
The following example shows this function, and its possible output, when used in a RETURN statement:
RETURN array::shuffle([ 1, 2, 3, 4, 5 ]); [ 2, 1, 4, 3, 5 ]
array::sliceThe array::slice function returns a slice of an array, based on a starting position, and a length or negative position.
API DEFINITIONarray::slice(array, start: int, len: int) -> array -- Also since 3.0.0-alpha.8 array::slice(array, range) -> array;
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::slice([ 1, 2, 3, 4, 5 ], 1, 2); [2, 3]
The following example shows how you can use this function with a starting position, and a negative position, which will slice off the first and last element from the array:
RETURN array::slice([ 1, 2, 3, 4, 5 ], 1, -1); [ 2, 3, 4 ]
The following example shows how you can use this function with just a starting position, which will only slice from the beginning of the array:
RETURN array::slice([ 1, 2, 3, 4, 5 ], 2); [ 3, 4, 5 ]
The following example shows how you can use this function with just a negative position, which will only slice from the end of the array:
RETURN array::slice([ 1, 2, 3, 4, 5 ], -2); [ 4, 5 ]
The following example shows how you can use this function with a negative position, and a length of the slice:
RETURN array::slice([ 1, 2, 3, 4, 5 ], -3, 2); [ 3, 4 ]
An example of post SurrealDB 3.0 syntax in which the function can also take a range:
['a', 'b', 'c', 'd', 'e'].slice(2..=3); [ 'c', 'd' ]
array::sortThe array::sort function sorts the values in an array in ascending or descending order.
API DEFINITIONarray::sort(array) -> array
The function also accepts a second boolean parameter which determines the sorting direction. The second parameter can be true for ascending order, or false for descending order.
API DEFINITIONarray::sort(array, bool) -> array
The function also accepts a second string parameter which determines the sorting direction. The second parameter can be 'asc' for ascending order, or 'desc' for descending order.
API DEFINITIONarray::sort(array, string) -> array
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::sort([ 1, 2, 1, null, "something", 3, 3, 4, 0 ]); [ null, 0, 1, 1, 2, 3, 3, 4, "something" ]
RETURN array::sort([1, 2, 1, null, "something", 3, 3, 4, 0], false); [ "something", 4, 3, 3, 2, 1, 1, 9, null ]
RETURN array::sort([1, 2, 1, null, "something", 3, 3, 4, 0], "asc"); [ null, 0, 1, 1, 2, 3, 3, 4, "something" ]
RETURN array::sort([1, 2, 1, null, "something", 3, 3, 4, 0], "desc"); [ "something", 4, 3, 3, 2, 1, 1, 9, null ]
array::sort_lexicalNoteOnly available in nightly, will be available in the next release.
The array::sort_natural_lexical function sorts the values in an array in ascending or descending order, with alphabetical strings sorted in lexical order instead of unicode list order.
API DEFINITIONarray::sort_lexical(array) -> array
The function also accepts a second boolean parameter which determines the sorting direction. The second parameter can be true for ascending order, or false for descending order.
API DEFINITIONarray::sort_lexical(array, bool) -> array
The function also accepts a second string parameter which determines the sorting direction. The second parameter can be 'asc' for ascending order, or 'desc' for descending order.
API DEFINITIONarray::sort_lexical(array, string) -> array
The following example shows that array::sort_lexical will sort strings in lexical (alphabetical) order instead of Unicode list order. As an accented ‘Á’ is listed later in Unicode than regular ASCII letters, the function array::sort will show the name ‘Álvares’ listed after the word ‘senhor’, but array::sort_lexical will show the name at the front of the array instead.
['Obrigado', 'senhor', 'Álvares'].sort(); ['Obrigado', 'senhor', 'Álvares'].sort_lexical();
Output-------- Query 1 (443.209µs) -------- [ 'Obrigado', 'senhor', 'Álvares' ] -------- Query 2 (457.542µs) -------- [ 'Álvares', 'Obrigado', 'senhor' ]
array::sort_naturalNoteOnly available in nightly, will be available in the next release.
The array::sort_natural function sorts the values in an array in ascending or descending order, with numeric strings sorted in numeric order instead of regular string order.
API DEFINITIONarray::sort_natural(array) -> array
The function also accepts a second boolean parameter which determines the sorting direction. The second parameter can be true for ascending order, or false for descending order.
API DEFINITIONarray::sort_natural(array, bool) -> array
The function also accepts a second string parameter which determines the sorting direction. The second parameter can be 'asc' for ascending order, or 'desc' for descending order.
API DEFINITIONarray::sort_natural(array, string) -> array
The following example shows that array::sort_natural will sort numeric strings as if they were numbers. The array::sort function, on the other hand, treats a string like ‘3’ as greater than ‘11’ due to the first character in ‘3’ being greater than ‘1’.
Note that strings sorted in numeric order will still appear after actual numbers, as a string will always be greater than a number.
[8, 9, 10, '3', '2.2', '11'].sort(); [8, 9, 10, '3', '2.2', '11'].sort_natural();
Output-------- Query -------- [ 8, 9, 10, '11', '2.2', '3' ] -------- Query 2 (332.667µs) -------- [ 8, 9, 10, '2.2', '3', '11' ]
array::sort_natural_lexicalNoteOnly available in nightly, will be available in the next release.
The array::sort_natural_lexical function sorts the values in an array in ascending or descending order, while sorting numeric strings in numeric order and alphabetical strings in lexical order.
API DEFINITIONarray::sort_natural_lexical(array) -> array
The function also accepts a second boolean parameter which determines the sorting direction. The second parameter can be true for ascending order, or false for descending order.
API DEFINITIONarray::sort_natural_lexical(array, bool) -> array
The function also accepts a second string parameter which determines the sorting direction. The second parameter can be 'asc' for ascending order, or 'desc' for descending order.
API DEFINITIONarray::sort_natural_lexical(array, string) -> array
The following example shows that array::sort_natural_lexical will sort numeric strings as if they were numbers, and alphabetical strings in lexical order instead of Unicode order. The array::sort function, on the other hand, treats a string like ‘3’ as greater than ‘11’ due to the first character in ‘3’ being greater than ‘1’, and sorts the name ‘Álvares’ after the string ‘senhor’ because the ‘Á’ character comes after regular ASCII characters in Unicode.
['Obrigado', 'senhor', 'Álvares', 8, 9, 10, '3', '2.2', '11'].sort(); ['Obrigado', 'senhor', 'Álvares', 8, 9, 10, '3', '2.2', '11'].sort_natural_lexical();
Output-------- Query -------- [ 8, 9, 10, '11', '2.2', '3', 'Obrigado', 'senhor', 'Álvares' ] -------- Query 2 (332.667µs) -------- [ 8, 9, 10, '2.2', '3', '11', 'Álvares', 'Obrigado', 'senhor' ]
array::sort::ascThe array::sort::asc function is a shorthand convenience function for the array::sort function, to sort values in an array in ascending order.
API DEFINITIONarray::sort::asc(array) -> array
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::sort::asc([ 1, 2, 1, null, "something", 3, 3, 4, 0 ]); [ null, 0, 1, 1, 2, 3, 3, 4, "something" ]
array::sort::descThe array::sort::desc function is a shorthand convenience function for the array::sort function, to sort values in an array in descending order.
API DEFINITIONarray::sort::desc(array) -> array
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::sort::desc([ 1, 2, 1, null, "something", 3, 3, 4, 0 ]); [ "something", 4, 3, 3, 2, 1, 1, 9, null ]
array::swapAvailable since: v2.0.0
The array::swap function swaps two values of an array based on indexes.
API DEFINITIONarray::swap(array, from: int, to: int) -> array
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::swap(["What's", "its", "got", "in", "it", "pocketses?"], 1, 4);
Output[ "What's", 'it', 'got', 'in', 'its', 'pocketses?' ]
The following example shows how you can use this function with a positive index, and a negative index, which will swap the first and last element from the array:
RETURN array::swap([ 1, 2, 3, 4, 5 ], 0, -1); [ 5, 2, 3, 4, 1 ]
An error will be returned if any of the indexes are invalid that informs of range of possible indexes that can be used.
RETURN array::swap([0, 1], 100, 1000000);
Output'Incorrect arguments for function array::swap(). Argument 1 is out of range. Expected a number between -2 and 2'
array::transposeThe array::transpose function is used to perform 2d array transposition but its behavior in cases of arrays of differing sizes can be best described as taking in multiple arrays and ‘layering’ them on top of each other.
API DEFINITIONarray::transpose(array<array>) -> array<array>
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::transpose([[0, 1], [2, 3]]); [ [0, 2], [1, 3] ]
The layering of the above example can be visualized as follows.
0 1 2 3 ↓ ↓ 0 1 2 3
Imagining a Rubik’s Cube is another easy way to conceptualize this function.
RETURN array::transpose([ ['🟦', '🟥', '🟩'], ['⬜', '🟦', '🟨'], ['🟧', '🟧', '🟥'] ]);
The output shows the same blocks, but lined up top to bottom instead of left to right.
[ [ '🟦', '⬜', '🟧' ], [ '🟥', '🟦', '🟧' ], [ '🟩', '🟨', '🟥' ] ]
Another example of the function used for the statistics of two people:
[["Name", "Age"], ["Billy", 25], ["Alice", 30]].transpose();
Output[ [ 'Name', 'Billy', 'Alice' ], [ 'Age', 25, 30 ] ]
The logic of this function for arrays of differing length was improved in SurrealDB 2.2, in which NONE is now added at points in which no item is found at an index. Take the following movies for example, in which one — Groundhog Day — does not have a bad guy.
[ ['Movie', 'Bad guy'], ['Avengers: Infinity War', 'Thanos'], ['Groundhog Day'], ['Star Wars', 'Palpatine'] ].transpose();
[ [ 'Movie', 'Avengers: Infinity War', 'Groundhog Day', 'Star Wars' ], [ 'Bad guy', 'Thanos', NONE, 'Palpatine' ] ]
[ [ 'Movie', 'Avengers: Infinity War', 'Groundhog Day', 'Star Wars' ], [ 'Bad guy', 'Thanos', 'Palpatine' ] ]
This new behaviour allows transposed arrays to be transposed once more to restore the original output, except with NONE added in all the indexes that lack in any array.
[ [ 'Movie', 'Bad guy' ], [ 'Avengers: Infinity War', 'Thanos' ], [ 'Groundhog Day' ], [ 'Star Wars', 'Palpatine' ] ].transpose().transpose();
Output[ [ 'Movie', 'Bad guy' ], [ 'Avengers: Infinity War', 'Thanos' ], [ 'Groundhog Day', NONE ], [ 'Star Wars', 'Palpatine' ] ]
array::unionThe array::union function combines two arrays together, removing duplicate values, and returning a single array.
API DEFINITIONarray::union(array, array) -> array
The following example shows this function, and its output, when used in a RETURN statement:
RETURN array::union([1, 2, 1, 6], [1, 3, 4, 5, 6]); [ 1, 2, 6, 3, 4, 5 ]
array::windowsAvailable since: v2.0.0
API DEFINITIONarray::windows(array, size: int) -> array
The array::windows function returns a number of arrays of length size created by moving one index at a time down the original array. The arrays returned are guaranteed to be of length size. As a result, the function will return an empty array if the length of the original array is not large enough to create a single output array.
The following examples show this function, and its output, when used in a RETURN statement:
LET $array = [1, 2, 3, 4]; RETURN array::windows($array, 2); RETURN array::windows($array, 5);
Response[ [1, 2], [2, 3], [3, 4] ]; [];
An example of the same function used in a RELATE statement:
CREATE person:grandfather, person:father, person:son; FOR $pair IN array::windows(["grandfather", "father", "son"], 2) { LET $first = type::record("person", $pair[0]); LET $second = type::record("person", $pair[1]); RELATE $first->father_of->$second; }; SELECT id, ->father_of->person, ->father_of->father_of->person FROM person;
Available since: v2.0.0
Method chaining allows functions to be called using the . dot operator on a value of a certain type instead of the full path of the function followed by the value.
-- Traditional syntax array::push(["Again", "again"], "again"); -- Method chaining syntax ["Again", "again"].push("again");
Response["Again", "again", "again"]
This is particularly useful for readability when a function is called multiple times.
-- Traditional syntax array::join(array::push(["Again", "again"], "again")); -- Method chaining syntax ["Again", "again"].push("again").join(" and ");
Response"Again and again and again"