sumBy

sumBy<T>(array: Array<T>, numberSelector: (T) -> Number): Number

Returns the sum of the values of the elements in an array.

Parameters

Name Description

array

The input array.

numberSelector

A DataWeave selector that selects the values of the numbers in the input array.

Example

This example calculates the sum of the values of elements some arrays. Notice that both of the sumBy function calls produce the same result.

Source

%dw 2.0
import * from dw::core::Arrays
output application/json
---
{
  "sumBy" : [
    [ { a: 1 }, { a: 2 }, { a: 3 } ] sumBy $.a,
    sumBy([ { a: 1 }, { a: 2 }, { a: 3 } ], (item) -> item.a)
  ]
}

Output

{ "sumBy" : [ 6, 6 ] }

sumBy(array: Null, numberSelector: (Nothing) -> Any): Null

Helper function that enables sumBy to work with a null value.

Introduced in DataWeave version 2.4.0.

Was this article helpful?

💙 Thanks for your feedback!

Edit on GitHub