---
schema_version: "1"
id: 0e2929cfa556892b3d94c3889395b2c5d57cea0399cd18f1650085e53e82402b
title: countBy
collection: mulesoft
version: current
locale: en-us
portal_url: https://docs.salesforce.com/mulesoft/current/en-us/dataweave/2.9/dw-arrays-functions-countby.md
canonical_url: https://docs.mulesoft.com/dataweave/2.9/dw-arrays-functions-countby
source_site: docs.mulesoft.com
content_type: documentation
content_hash: 0280362b0a39cd9bead07ad93d17b32b7091ed8270c487a8d043102cf84274a2
description: MuleSoft Documentation Site
release: "2.9"
latest: false
---
---
product: DataWeave
version: 2.9
---

# countBy

> For the full documentation index, see: https://docs.mulesoft.com/llms.txt

## countBy<T>(@StreamCapable 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

<table><colgroup><col> <col></colgroup><thead><tr><th>Name</th><th>Description</th></tr></thead><tbody><tr><td><p><code>array</code></p></td><td><p>The input array that contains elements to match.</p></td></tr><tr><td><p><code>matchingFunction</code></p></td><td><p>A function to apply to elements in the input array.</p></td></tr></tbody></table>

### 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.

#### Source

```DataWeave
%dw 2.0
import * from dw::core::Arrays
output application/json
---
{ "countBy" : [1, 2, 3, 4] countBy (($ mod 2) == 0) }
```

#### Output

```JSON
{ "countBy": 2 }
```

## countBy(array: Null, matchingFunction: (Nothing) -> Any): Null

Helper function that enables `countBy` to work with a `null` value.

_Introduced in DataWeave version 2.4.0._
