Unist Utility to Remove Nodes

4.0.0 · active · verified Sun Apr 19

unist-util-remove is a utility package within the unified ecosystem designed to modify unist (Universal Syntax Tree) structures by removing nodes that pass a given test. Unlike `unist-util-filter`, this utility mutates the tree in-place, which can offer significant performance benefits on large documents. The current stable version is 4.0.0, which notably introduced a requirement for Node.js 16+, transitioned to being an ESM-only package, and altered the return type of the `remove` function from the modified tree to `undefined`. The package maintains compatibility with actively maintained Node.js versions and receives updates for bug fixes, performance improvements, and minor enhancements. Major version releases typically align with Node.js LTS updates or significant architectural shifts within the unified ecosystem, such as the move to ESM.

Common errors

Warnings

Install

Imports

Quickstart

Demonstrates importing `remove` and using it to mutate a unist tree by removing nodes matching a type, including an example of the `cascade` option.

import { u } from 'unist-builder';
import { remove } from 'unist-util-remove';

// Create a sample unist tree
const tree = u('root', [
  u('leaf', '1'),
  u('parent', [
    u('leaf', '2'),
    u('parent', [u('leaf', '3'), u('other', '4')]),
    u('parent', [u('leaf', '5')])
  ]),
  u('leaf', '6'),
  u('emptyParent', [])
]);

console.log('Original Tree:');
console.dir(tree, { depth: undefined });

// Remove all nodes of type `leaf`.
// Note: `remove` mutates the tree in-place and returns undefined since v4.0.0.
remove(tree, 'leaf');

console.log('\nTree after removing all `leaf` nodes:');
console.dir(tree, { depth: undefined });

// Example with `cascade: false` to keep parents if only children were removed
const anotherTree = u('root', [
  u('parent', [
    u('removableChild', 'a'),
    u('keepableChild', 'b')
  ])
]);

console.log('\nOriginal Tree for cascade example:');
console.dir(anotherTree, { depth: undefined });

remove(anotherTree, { cascade: false }, 'removableChild');

console.log('\nTree after removing `removableChild` with cascade: false:');
console.dir(anotherTree, { depth: undefined });

view raw JSON →