Dark theme | Light theme

February 17, 2022

DataWeave Delight: Counting items in array with predicate

The dw::core::Arrays module has some nice functions that works with arrays. One of these functions is countBy. The function takes an array as first argument and a predicate function that accepts an item from the array and should return true or false. The total number of items that adhere to the predicate is the result of the countBy function.

In the following examples we use the countBy function with different predicates:


%dw 2.0

import countBy from dw::core::Arrays

var languages = ['DataWeave', 'Groovy', 'Java', 'Clojure']

output application/json
    // Count items that have more than 6 characters.
    sample1: languages countBy ((item) -> sizeOf(item) > 6), 

    // Count number of even numbers.
    sample2: 1 to 10 countBy (number) -> isEven(number),

    // Using shorthand notation $ to count upper case characters.
    sample3: ["AB", "cD", "Ef", "GH"] countBy dw::core::Strings::isUpperCase($)


  "sample1": 2,
  "sample2": 5,
  "sample3": 2

Written with DataWeave 2.4.