subarray()

Returns a sub-array from an array for the range defined by a start index and an end index.

Syntax

subarray(ARRAY, START[, END])

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:

  • ARRAY is null
  • START is out of the valid range
  • START is greater than END

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

  1. Specify only START to extract from that position to the end

    json "{}" | eval arr = subarray(array(1, 2, 3, 4, 5), 2)
    | # arr: [3, 4, 5]
    
  2. Specify both START and END to extract a specific range

    json "{}" | eval arr = subarray(array(1, 2, 3, 4, 5), 2, 4)
    | # arr: [3, 4]
    
  3. Use negative indices to define the range

    json "{}" | eval arr = subarray(array(1, 2, 3, 4, 5), 1, -1)
    | # arr: [2, 3, 4]
    
  4. START is out of the valid range

    json "{}" | eval arr = subarray(array(1, 2, 3, 4, 5), 5)
    | # arr: null
    
  5. ARRAY is null

    json "{}" | eval arr = subarray(null, 0)
    | # arr: null
    

Compatibility

subarray() has been available since before Sonar 4.0.