%dw 2.0
import * from dw::core::Arrays
output application/json
---
{ "countBy" : [1, 2, 3, 4] countBy (($ mod 2) == 0) }
countBy
countBy<T>(array: Array<T>, matchingFunction: (T) -> Boolean): Number
Counts the elements in an array that return true
when the matching function is applied to the value of each element.
Parameters
Name | Description |
---|---|
|
The input array that contains elements to match. |
|
A function to apply to elements in the input array. |
Example
This example counts the number of elements in the input array ([1, 2, 3, 4]) that
return true
when the function (($ mod 2) == 0)
is applied their values. In this
case, the values of two of the elements, both 2
and 4
, match because
2 mod 2 == 0
and 4 mod 2 == 0
. As a consequence, the countBy
function returns 2
.
Note that mod
returns the modulus of the operands.