Skip to content

sum

The 'sum' filter calculates and returns the sum of numerical values within an array or an array of objects. It offers flexibility by allowing you to sum the elements directly or sum the values of a specific property within the objects.

Functionality

  • Arrays of Numbers: Calculates the sum of all the numbers in the array.
  • Arrays of Objects: Calculates the sum of the values of a specified property within each object in the array.
  • Nested Arrays: Can handle nested arrays, summing the values at each level.
  • Mixed Data Types: Automatically converts string representations of numbers to their numerical values for calculation.

Syntax

    {{ array_variable | sum }} 

or

    {{ array_variable | sum: property_name }}

Arguments

  • property_name (optional): A string representing the name of the property to use for summing the values within the objects of the array. If omitted, the filter sums the elements directly, assuming they are numbers.

Code Samples

Example 1: Summing Numbers in an Array

    {% assign numbers = [5, 2, 8, 1] %}

    {{ numbers | sum }} 

Output:

16
Example 2: Summing a Property in an Array of Objects
    {% assign products = [{ "name": "Product A", "price": 10 }, 
                          { "name": "Product B", "price": 25 }, 
                          { "name": "Product C", "price": 15 }] %}

    {{ products | sum: "price" }}

Output:

50
Example 3: Summing Nested Arrays
    {% assign matrix = [[1, 2], [3, 4, 5]] %}

    {{ matrix | sum }}
Output:
15

Outliers and Special Cases

  • Empty Arrays: If the input array is empty, the sum filter returns 0.
  • Non-Numeric Values: If the array contains non-numeric values (when property_name is not provided), they are ignored in the calculation.
  • Invalid Property: If the specified property_name does not exist on the elements of the array, the filter may return an error or unexpected results (depending on Experience Builder's error handling).

Key Points

  • The sum filter is versatile for aggregating numerical data within arrays, whether the numbers are directly in the array or nested within objects.
  • It handles both simple number arrays and more complex data structures with ease.
  • Ensure that the data you're summing is of a numeric type (or can be converted to a number) to avoid errors.