The problem

Using QGIS expressions with QGIS 3.20, I have an array and I want to exclude a number of elements from this array. Let's say my array is [1,2,3,4,5,6], but I want to get an array like [1,2,3], removing [4,5,6] from the initial array.

What I tried I

There is a function array_remove_all (array,value), but with this, you can just remove one element: array_remove_all (array (1,2,3,4,5,6),6) reults in: [ 1, 2, 3, 4, 5 ]. I would like, basically, "subtract" one array from another array, pseudocode:

array_subtract (array(1,2,3,4,5,6), array(4,5,6)) -> [1,2,3].

array_slice is not what I'm looking for as it is based on start- and end-position.

What I tried II: a workaround

A workaround is this, but the if-condition expects an else-value, here: 'x'. If I could avoid creating an element in the array in case the if-condition is false, the problem would be solved, But like this, I have to create an output like 'x' - even an empty output like '' creates an element in the array:

array_foreach (
    array (1,2,3,4,5,6),
    if (
        @element <=3,

returns: [ 1,2,3,'x', 'x', 'x' ]

Now, the 'x' can be removed with:

array_remove_all( array (1,2,3,'x', 'x', 'x'), 'x')

finally returns: [ 1, 2, 3 ]

What I tried II: another workaround

Using a case-statement instead of the if-condition to avoid an else-value does not help, as it still produces NULL-elements in the array that I then have to remove:

array_foreach (
    array (1,2,3,4,5,6),
    when @element <=3 then @element

returns: [ 1, 2, 3, NULL, NULL, NULL ]

The Question

Is there a better solution to this?


You can use array_filter() combined with in operator, like:

array_filter(array(1,2,3,4,5,6), @element not in (4,5,6))

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.