---
title: "filter"
description: "Filter a tree by a predicate, keeping matching nodes along with their ancestors so the surviving branches remain navigable."
canonical_url: "https://core.mhaibaraai.cn/en/docs/transformers/tree/filter"
---
# filter

> Filter a tree by a predicate, keeping matching nodes along with their ancestors so the surviving branches remain navigable.

## Usage

The `filter` method filters a tree based on a `predicate` function. Unlike array's `filter`, it retains all nodes that satisfy the condition as well as their ancestor nodes, thereby maintaining the tree structure.

```ts [example.ts]
import { Tree } from '@movk/core'

const tree = [
  { id: 1, name: 'Root', children: [
    { id: 2, name: 'Active User' },
    { id: 3, name: 'Inactive User', children: [{ id: 4, name: 'Active Child' }] }
  ] }
]

const activeTree = Tree.filter(tree, ({ node }) => node.name.includes('Active'))

/*
activeTree will be:
[
  { id: 1, name: 'Root', children: [
    { id: 2, name: 'Active User', children: [] },
    { id: 3, name: 'Inactive User', children: [{ id: 4, name: 'Active Child', children: [] }] }
  ]}
]
*/
```

## API

`filter<T extends TreeNode>(tree: T[], predicate: (context: VisitorContext<T>) => boolean, config?: TreeConfig): T[]`

### Parameters

**tree** (`T[]`) *required*: The source tree array.

**predicate** (`(context: VisitorContext<T>) => boolean`) *required*: A predicate function called for each node in the tree. If the function returns true, that node and all its ancestor nodes will be retained in the result.
The function receives a context object with the following properties:The node currently being processed.The depth of the node (root node is 0).An array of nodes from the root to the current node (inclusive).The index of the current node among its siblings.

**config** (`TreeConfig`): Configuration object for customizing the id, pid, children key names in the tree structure.Optional. The key name for the node's unique identifier. Defaults to "id".Optional. The key name for the node's parent identifier. Defaults to "pid".Optional. The key name for the children array. Defaults to "children".

### Returns

**T[]**: Returns a new, filtered tree array.

## Changelog

See commit history for [src/transformers/tree/transform.ts](https://github.com/mhaibaraai/movk-core/commits/main/src/transformers/tree/transform.ts).

---

- [GitHub](https://github.com/mhaibaraai/movk-core/blob/main/src/transformers/tree/transform.ts)


## Sitemap

See the full [sitemap](https://core.mhaibaraai.cn/sitemap.md) for all pages.
