Aggregates the elements of an array into a single value using an accumulator and a lambda expression.
Syntax
R array_reduce(array<T> <a>, buf <init>, function<buf, T, buf> <merge>, function<buf, R> <final>)Parameters
| Parameter | Required | Description |
|---|---|---|
a | Yes | The input array. T in array<T> is the element data type, which can be any supported type. |
init | Yes | The initial value of the accumulator (buf). This is the starting state before any element is processed. |
merge | Yes | A built-in function, user-defined function, or lambda expression that processes each element in a against the current accumulator. Takes buf and the current element as inputs, and returns an updated buf. |
final | Yes | A built-in function, user-defined function, or lambda expression that converts the accumulator into the final output. Takes the result of merge as input. R specifies the return type. If no conversion is needed, pass the identity expression buf->buf. |
Return value
The return type matches the type specified by the final parameter (R).
Examples
Sum all elements
-- Returns 6
select array_reduce(array(1, 2, 3), 0, (buf, e)->buf + e, buf->buf);The merge expression (buf, e)->buf + e adds each element to the accumulator. The final expression buf->buf is the identity function — it returns the accumulator as-is without any type conversion.
Calculate an average
-- Returns 2.5
select array_reduce(array(1, 2, 3, 4), named_struct('sum', 0, 'count', 0), (buf, e)->named_struct('sum', buf.sum + e, 'count', buf.count + 1), buf -> buf.sum / buf.count);The accumulator is a STRUCT with two fields: sum and count. The merge expression updates both fields for each element. The final expression computes the average by dividing sum by count.
Related functions
ARRAY_REDUCE is a complex type function. For more information about functions related to the processing of data of complex data types, such as ARRAY, MAP, STRUCT, and JSON, see Complex type functions.
In the preceding examples, the combination of a hyphen and a closing angle bracket
(->)is used. For more information about how to use the combination of a hyphen and a closing angle bracket(->)in Lambda functions, see Lambda functions.