ModelWorks logoModelWorks
JSON TransformArray

findIndex

Return the index of the first element matching a JMESPath condition

findIndex

Walks the array and returns the zero-based index of the first element whose JMESPath expression evaluates to true. Returns -1 if nothing matches.

Options

OptionTypeRequiredDefaultDescription
expressionstringYesJMESPath boolean expression. item and @ refer to the current element.

Example

Input

JSON
[
  { "id": 1, "role": "user" },
  { "id": 2, "role": "assistant" },
  { "id": 3, "role": "user" }
]

Operation

JSON
{ "type": "findIndex", "options": { "expression": "item.role == `assistant`" } }

Output

JSON
1

In a Circuit Step

JSON
{
  "name": "locate_assistant_turn",
  "description": "Find the index of the first assistant message",
  "function": "circuit.core.transform.json",
  "input": {
    "source": "${{ messages }}",
    "operations": [
      { "type": "findIndex", "options": { "expression": "item.role == `assistant`" } }
    ]
  },
  "outputs": [
    {
      "name": "first_assistant_index",
      "description": "Index of the first assistant message, or -1",
      "value": "${{ locate_assistant_turn.output.transformed_result }}"
    }
  ]
}

Notes & gotchas

  • Errors with findIndex: expected array if the input is not an array.
  • Returns -1 when no element matches — note this is a JSON number, not null.
  • The expression must resolve to a JSON boolean true; anything else is a non-match.
  • For richer scans (e.g., return the matching element itself), use find.
On this page

On this page