QGIS – How to Get More Than One Element from Array Using Square Brackets in QGIS Expressions

arrayexpressionqgis

Using QGIS expressions, if you have an array, you can get the n-th element by simply adding a number (n) in square brackets (starting with 0 for the first element). Like this, array (1,2,3,4,5,6,7,8)[2] returns 3 (element no. 2/third element).

Is there a way to retrieve more than one element in this way with QGIS expressions?

What I tried, based on similar options in R, but doesn't work here:

array (1,2,3,4,5,6,7,8)[2,3] — to retrieve elements 2 and 3
array (1,2,3,4,5,6,7,8)[array(2,5)] — to retrieve elements 2, 3 and 5

Best Answer

I guess no. At least in Python they are called index brackets and are not meant to contain several indizes. Don't know about other languages like R or C. But you can build a custom function:

from qgis.core import *
from qgis.gui import *

@qgsfunction(args='auto', group='Custom', referenced_columns=[])
# arr is an array-input you want to return several values from by their index
# idxarr is an array-input containing the indizes you want to return from arr
def array_get_several(arr, idxarr, feature, parent):
    elements = [arr[i] for i in idxarr]
    return elements

and use it as array_get_several(array(1,2,3,4,5,6),array(1,2)) which for example returns [2,3]. Note that it returns the values ordered, so e.g. array_get_several(array(1,2,3,4,5,6),array(2,1)) does return [3,2].