---
schema_version: "1"
id: b939d5b9ab507297c9631092e0bb178161ba05d8b6b3323490109a8d2ce6f83c
title: countBy
collection: mulesoft
version: current
locale: en-us
portal_url: https://docs.salesforce.com/mulesoft/current/en-us/dataweave/latest/dw-arrays-functions-countby.md
canonical_url: https://docs.mulesoft.com/dataweave/latest/dw-arrays-functions-countby
source_site: docs.mulesoft.com
content_type: documentation
content_hash: 1c1b2bbc6ecf904b06d7d8d62e3de621ef32a2d85d1a2b154bc9d89247505ac9
description: MuleSoft Documentation Site
release: "2.13"
latest: true
---
---
product: DataWeave
version: 2.13
is-latest-version: true
---

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