Skip to main content

array.reduce(function)

Reduces an array to a single value

Availability

Device + Agent

Parameters

Name Type Description
function Function A reduction function

Returns

Any Squirrel data type

Description

This method applies the supplied function to all of the items in the target array, starting with the first two. The function returns a single value which is then combined with the next (third) item in the array — and so on until all of the items have been combined into a single value which the method returns.

The reduction function must include two parameters: the result returned by its previous iteration and the next item in the array — reduce() takes care of iterating through the target array’s items.

If the target array contains just a single item, that item will be the value that is returned. If the target contains no items, reduce() will return null.

Example Code

The example below shows the use of reduce() to add the elements of the array sourceArray. The function used to perform the reduction can be simplified further if we use a Squirrel lambda function, and this is shown in the second example.

The third example shows how reduce() can be used on an array of string segments (generated by splitting a source string into sub-strings separated by a newline) to reassemble the string after processing.