In DataWeave we can calculate the average for an array of numbers with the avg function. If we want to calculate the average for other types in an array or object if we first transform the source object to an array of numbers.

In the following example we use the avg function:

Source

%dw 2.0

var numbers = [10, 20, 30, 40, 50]

var words = ["MuleSoft", "DataWeave", "Delight"]

var books = [
    {
        title: "Lord of the rings",
        price: 30.0
    },
    {
        title: "Hitch-hiker's guide to the galaxy",
        price: 42.0
    }
]

output application/json
---
{
    // Average for a array of numbers.
    average: avg(numbers),

    // We can map our source objects to number values
    // and calculate the average.
    averageWordSize: avg(words map sizeOf($)),

    // The array of book object can be turned into
    // an array with only the prices and we can
    // calculate the average.
    averageBookPrice: avg(books map $.price)
}

Output

{
  "average": 30,
  "averageWordSize": 8,
  "averageBookPrice": 36.0
}
DataWeave is a functional language designed by MuleSoft for transforming data structures defined in for example JSON, XML or CSV.

Written with DataWeave 2.4.

shadow-left