insertBefore

Insert a new node immediately before a target node in a tree by id, returning whether the insertion succeeded.

Usage

The insertBefore method inserts a new node immediately before the target node (found by id). This method mutates the tree array in place.

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

const tree = [{ id: 1, name: 'A' }, { id: 2, name: 'C' }]
const newNode = { id: 3, name: 'B' }

Tree.insertBefore(tree, newNode, 2)

/*
tree will be:
[{ id: 1, name: 'A' }, { id: 3, name: 'B' }, { id: 2, name: 'C' }]
*/

API

insertBefore<T extends TreeNode>(tree: T[], node: T, targetId: number | string, config?: TreeConfig): boolean

Parameters

tree
T[] required
The source tree array.
node
T required
The new node to insert.
targetId
number | string required
The ID of the target node. The new node will be inserted before this node.
config
TreeConfig
Configuration object for customizing the id, pid, children key names in the tree structure.

Returns

boolean
Returns true if the target was found and the new node was successfully inserted, otherwise false.

Changelog

No recent changes
Copyright © 2024 - 2026 YiXuan - MIT License