Unist Utility to Filter Nodes

5.0.1 · active · verified Sun Apr 19

unist-util-filter is a utility for the Unist ecosystem that creates a new, immutable tree containing only the nodes that pass a provided test function. Unlike `unist-util-remove`, which modifies the original tree in place, `unist-util-filter` ensures immutability, making it suitable for functional programming paradigms or scenarios where the original tree must be preserved. The current stable version is 5.0.1. Major releases are not on a fixed cadence but often coincide with updates to Node.js LTS lines and significant changes in TypeScript definitions or module resolution. It integrates seamlessly with `unist-util-is` for defining complex testing conditions and offers a `cascade` option to control whether parent nodes should be removed if all their children are filtered out, with `true` as the default. This utility provides a clean, predictable way to prune ASTs without side effects.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates filtering a Unist tree to retain only parent nodes and leaf nodes with even values, showing the immutable nature of the operation.

import {u} from 'unist-builder'
import {filter} from 'unist-util-filter'

const tree = u('root', [
  u('leaf', '1'),
  u('parent', [u('leaf', '2'), u('parent', [u('leaf', '3')])]),
  u('leaf', '4')
])

const newTree = filter(tree, node => node.type !== 'leaf' || Number(node.value) % 2 === 0)

console.dir(newTree, {depth: null})

/*
Yields:
{
  type: 'root',
  children: [
    {type: 'parent', children: [{type: 'leaf', value: '2'}]},
    {type: 'leaf', value: '4'}
  ]
}
*/

view raw JSON →