QGIS – Returning Majority of Array Elements Using Field Calculator Expression

expressionfield-calculatorqgis

I need to identify the majority of a string in an attribute field. For example 'A,AB,C,A' -> 'A'

Since QGIS 3.18 the function array_majority() is available.

However, I use the latest stable version 3.16 and I am wondering if something similar can be done?

Something like:

array_to_string(majority(string_to_array("sumEHZ")))

Best Answer

In QGIS 3.16, you can use this expression, where text is the field containing the text you want to replace:

with_variable (
    'var',
    'array_foreach (
        array_distinct (string_to_array ("text")),
        with_variable (
            ''arr'',
               @element,
               array_length (
                array_filter (
                    string_to_array("text"),
                       @element=@arr
                )
            )
        )
    )',
    array_get (
        array_distinct (string_to_array("text")),
        array_find (
            eval(@var),
            array_get (
                array_sort (
                    eval(@var),0
                ),0
            )
        )
    )
)

Expression edited, the repeating part from the initial expression is created as a variable var and called twice with eval(@var) to make the expression a bit shorter. See the screenshot for the (otherwise unchanged) initial expression: enter image description here

Related Question