subarray()
Returns a sub-array from an array for the range defined by a start index and an end index.
Syntax
Parameters
ARRAY- The array from which to extract a sub-array.
START- The index at which to start extraction. Starts at
0. A negative value counts from the end of the array. END- The index at which to stop extraction (optional). The element at this index is not included in the result. If omitted, extraction continues to the end of the array. A negative value counts from the end of the array.
Description
The subarray() function extracts elements from ARRAY in the range from START (inclusive) to END (exclusive) and returns them as a new array. Indices start at 0, and negative indices indicate positions from the end of the array. For example, in an array of length 5, -1 refers to the last element (index 4).
The function returns null in the following situations:
ARRAYisnullSTARTis out of the valid rangeSTARTis greater thanEND
If END is greater than the array length, all elements up to the end of the array are included.
Error codes
N/A
Usage examples
-
Specify only
STARTto extract from that position to the endjson "{}" | eval arr = subarray(array(1, 2, 3, 4, 5), 2) | # arr: [3, 4, 5] -
Specify both
STARTandENDto extract a specific rangejson "{}" | eval arr = subarray(array(1, 2, 3, 4, 5), 2, 4) | # arr: [3, 4] -
Use negative indices to define the range
json "{}" | eval arr = subarray(array(1, 2, 3, 4, 5), 1, -1) | # arr: [2, 3, 4] -
STARTis out of the valid rangejson "{}" | eval arr = subarray(array(1, 2, 3, 4, 5), 5) | # arr: null -
ARRAYisnulljson "{}" | eval arr = subarray(null, 0) | # arr: null
Compatibility
subarray() has been available since before Sonar 4.0.