Contact Us 1-800-596-4880

firstWith

firstWith<T>(array: Array<T>, condition: (item: T, index: Number) -> Boolean): T | Null

Returns the first element that satisfies the condition, or returns null if no element meets the condition.

Introduced in DataWeave version 2.3.0.

Parameters

Name Description

array

The array of elements to search.

condition

The condition to satisfy.

Example

This example shows how firstWith behaves when an element matches and when an element does not match.

Source

%dw 2.0
output application/json
import firstWith from dw::core::Arrays
var users = [{name: "Mariano", lastName: "Achaval"}, {name: "Ana", lastName: "Felisatti"}, {name: "Mariano", lastName: "de Sousa"}]
---
{
  a: users firstWith ((user, index) -> user.name == "Mariano"),
  b: users firstWith ((user, index) -> user.name == "Peter")
}

Output

{
  "a": {
    "name": "Mariano",
    "lastName": "Achaval"
  },
  "b": null
}

firstWith(array: Null, condition: (item: Nothing, index: Nothing) -> Any): Null

Helper function that enables firstWith to work with a null value.

Introduced in DataWeave version 2.4.0.