Skip to content
ENG

Create a function

Given the following input payload:

[
[
5,
6
],
[
100,
12
]
]

Write a DataWeave transformation that produces the following output:

123

Which is the result of summing every value across the two Arrays of numbers (5 + 6 + 100 + 12). You are expected to write a function that performs this total sum and works no matter how many elements the two Arrays hold.

  • To get the total sum of the values in a single array, you can use the sum(<Array<Number>>) function.
  • To concatenate Arrays (turn the two into one) you can use the ++(<Array<Number>>, <Array<Number>>) function.

🔒🔓Show solution
%dw 2.0
output application/json
fun sumar(n1: Array<Number>, n2: Array<Number>): Number = sum(n1 ++ n2)
// Otra forma de hacerlo
// fun sumar(n1: Array<Number>, n2: Array<Number>): Number = sum(n1) + sum(n2)
---
payload[0] sumar payload[1]

Notes:

  1. As mentioned in the hint, the sum() function returns the total sum of the values inside a numeric Array, so all that’s left is to add the total of the first Array to the total of the second one.
  2. Since ++ concatenates Arrays, we can build a single Array with all the elements and use sum() to get the total.
{Code mat;}

Learn MuleSoft: courses, exercises and quizzes. Free, no sign-up.