The big three of functional programming are functions map, filter and reduce. All three take functions as arguments which makes them functions of higher order. They can also be used in languages following the imperative programming approach if, for whatever reason, we want to avoid using classical loops to iterate over a sequence of elements.
Let us take a look at map, a higher order function. From map's function signature found in the documentation we can see that it takes two arguments (an array and a lambda expression) and returns an array.
T in Array
Map transforms elements in an array, creates a new array and saves the modified values into it. In simpler words, map maps elements of one array to the elements of another. The role of a lambda expression in map is to describe the transformation to be applied to each of the elements of the input array.
Filter removes elements in an array according to a lambda expression. Given the nature of the filter function, the purpose of its second argument, the lambda expression, is to return a boolean. The lambda expression serves as a condition here.
Of course, filter does not really remove any data since data in DataWeave is immutable. It selects elements based on a condition, i.e. filters an array, to be saved into the returned array of the same type.
Reduce reduces all the elements in an array down to a single element.
Its lambda expression should return a new value to the accumulator. The accumulator can be a single value but also a multi-value type like an array or an object. The output type of reduce is set by the accumulator and the lambda expression.
Reduce could therefore be used instead of map or filter. However, even if it is just due to inertia, it is often easier to stick to map and filter as usual and use reduce for simpler reduction tasks. Most developers encounter map and filter much more often than reduce.
LATEST FORUM UPDATES