All Projects → philipstanislaus → performant-array-to-tree

philipstanislaus / performant-array-to-tree

Licence: other
Converts an array of items with ids and parent ids to a nested tree in a performant O(n) way. Runs in browsers and Node.js.

Programming Languages

typescript
32286 projects

Projects that are alternatives of or similar to performant-array-to-tree

Angular2 Tree Diagram
Angular Hierarchical UI module
Stars: ✭ 50 (-74.09%)
Mutual labels:  tree, tree-structure
Bplustree
A minimal but extreme fast B+ tree indexing structure demo for billions of key-value storage
Stars: ✭ 1,598 (+727.98%)
Mutual labels:  tree, tree-structure
Ki
Go language (golang) full strength tree structures (ki in Japanese)
Stars: ✭ 61 (-68.39%)
Mutual labels:  tree, tree-structure
tree-json-generator
Simple JavaScript Tree Generator library
Stars: ✭ 13 (-93.26%)
Mutual labels:  tree, tree-structure
Relation Classification Using Bidirectional Lstm Tree
TensorFlow Implementation of the paper "End-to-End Relation Extraction using LSTMs on Sequences and Tree Structures" and "Classifying Relations via Long Short Term Memory Networks along Shortest Dependency Paths" for classifying relations
Stars: ✭ 167 (-13.47%)
Mutual labels:  tree, tree-structure
Wmderland
🌳 X11 tiling window manager using space partitioning trees
Stars: ✭ 341 (+76.68%)
Mutual labels:  tree, tree-structure
Abp.generaltree
For Abp vNext
Stars: ✭ 106 (-45.08%)
Mutual labels:  tree, tree-structure
stefano-tree
Framework agnostic Nested Set (MPTT) implementation for PHP
Stars: ✭ 24 (-87.56%)
Mutual labels:  tree, tree-structure
Graphview
Flutter GraphView is used to display data in graph structures. It can display Tree layout, Directed and Layered graph. Useful for Family Tree, Hierarchy View.
Stars: ✭ 152 (-21.24%)
Mutual labels:  tree, tree-structure
Array To Tree
Convert a plain array of nodes (with pointers to parent nodes) to a nested data structure
Stars: ✭ 141 (-26.94%)
Mutual labels:  tree, tree-structure
react-treefold
A renderless tree component for your hierarchical React views
Stars: ✭ 37 (-80.83%)
Mutual labels:  tree, tree-structure
mongodb-tree-structure
Implementing Tree Structure in MongoDB
Stars: ✭ 14 (-92.75%)
Mutual labels:  tree, tree-structure
qverse
Traverse any data with DPML commands.
Stars: ✭ 25 (-87.05%)
Mutual labels:  tree, traverse
Bosket
Collection of tree view components for front-end frameworks. 🌳
Stars: ✭ 457 (+136.79%)
Mutual labels:  tree, tree-structure
prune
A tree library for Java 8 with functional sensibilities.
Stars: ✭ 22 (-88.6%)
Mutual labels:  tree, tree-structure
Buckets Js
A complete, fully tested and documented data structure library written in pure JavaScript.
Stars: ✭ 1,128 (+484.46%)
Mutual labels:  tree, tree-structure
TreeRep
Learning Tree structures and Tree metrics
Stars: ✭ 18 (-90.67%)
Mutual labels:  tree, tree-structure
treetime
TreeTime is a data organisation, management and analysis tool. A tree is a hierarchical structure that arranges information in units and sub-units. TreeTime uses linked trees (one data item can be part of different distinct trees) to store and organise any general purpose data.
Stars: ✭ 26 (-86.53%)
Mutual labels:  tree, tree-structure
Containers
This library provides various containers. Each container has utility functions to manipulate the data it holds. This is an abstraction as to not have to manually manage and reallocate memory.
Stars: ✭ 125 (-35.23%)
Mutual labels:  tree, tree-structure
ng-treetable
A treetable module for angular 5
Stars: ✭ 32 (-83.42%)
Mutual labels:  tree, tree-structure

Performant array to tree

npm version minified size CircleCI codecov Dependency Status typings included npm license

Converts an array of items with ids and parent ids to a nested tree in a performant way (time complexity O(n)). Runs in browsers and node.

Why another package

Other packages have stricter assumptions or are not as performant, as they often use nested loops or recursion. For example:

o-unflatten requires the input to be ordered such that parent nodes always come before their children. un-flatten-tree uses 2 nested loops (time complexity O(n^2)).

This implementation does not require any order of items in the input array and focuses on runtime performance. It is the fastest amongst 4 different packages, you can find the benchmarks here. It uses an index and a single loop (time complexity O(n)). It was inspired by this discussion on StackOverflow.

Installation

yarn add performant-array-to-tree

or if using npm

npm install --save performant-array-to-tree

Usage

const tree = arrayToTree([
  { id: "4", parentId: null, custom: "abc" },
  { id: "31", parentId: "4", custom: "12" },
  { id: "1941", parentId: "418", custom: "de" },
  { id: "1", parentId: "418", custom: "ZZZz" },
  { id: "418", parentId: null, custom: "ü" },
]);

Which results in the following array:

[
  {
    data: { id: "4", parentId: null, custom: "abc" },
    children: [
      { data: { id: "31", parentId: "4", custom: "12" }, children: [] },
    ],
  },
  {
    data: { id: "418", parentId: null, custom: "ü" },
    children: [
      { data: { id: "1941", parentId: "418", custom: "de" }, children: [] },
      { data: { id: "1", parentId: "418", custom: "ZZZz" }, children: [] },
    ],
  },
];

Configuration

You can provide a second argument to arrayToTree with configuration options. Right now, you can set the following:

  • id: Key of the id field of the item. Also works with nested properties (e. g. "nested.parentId"). Default: "id".
  • parentId: Key of the parent's id field of the item. Also works with nested properties (e. g. "nested.parentId"). Default: "parentId".
  • nestedIds: Option to enable/disable nested ids. Default: true.
  • childrenField: Key which will contain all child nodes of the parent node. Default: "children"
  • dataField: Key which will contain all properties/data of the original items. Set to null if you don't want a container. Default: "data"
  • throwIfOrphans: Option to throw an error if the array of items contains one or more items that have no parents in the array or if the array of items contains items with a circular parent/child relationship. This option has a small runtime penalty, so it's disabled by default. When enabled, the function will throw an error containing the parentIds that were not found in the items array, or in the case of only circular item relationships a generic error. The function will throw an error if the number of nodes in the tree is smaller than the number of nodes in the original array. When disabled, the function will just ignore orphans and circular relationships and not add them to the tree. Default: false
  • rootParentIds: Object with parent ids as keys and true as values that should be considered the top or root elements of the tree. This is useful when your tree is a subset of full tree, which means there is no item whose parent id is one of undefined, null or ''. The array you pass in will be replace the default value. undefined and null are always considered to be rootParentIds. For more details, see #23. Default: {'': true}
  • assign: Option that enables Object.assign instead of the spread operator to create an item in the tree when dataField is null. This is useful if your items have a prototype that should be maintained. If enabled and dataField is null, the original node item will be used, and the children property will be assigned, calling any setters on that field. If dataField is not null, this option has no effect, since the original node will be used under the dataField of a new object. If you are unsure whether you need to enable this, it's likely fine to leave it disabled. Default: false

Example:

const tree = arrayToTree(
  [
    { num: "4", ref: null, custom: "abc" },
    { num: "31", ref: "4", custom: "12" },
    { num: "1941", ref: "418", custom: "de" },
    { num: "1", ref: "418", custom: "ZZZz" },
    { num: "418", ref: null, custom: "ü" },
  ],
  { id: "num", parentId: "ref", childrenField: "nodes" }
);

Which produces:

[
  {
    data: { num: "4", ref: null, custom: "abc" },
    nodes: [{ data: { num: "31", ref: "4", custom: "12" }, nodes: [] }],
  },
  {
    data: { num: "418", ref: null, custom: "ü" },
    nodes: [
      { data: { num: "1941", ref: "418", custom: "de" }, nodes: [] },
      { data: { num: "1", ref: "418", custom: "ZZZz" }, nodes: [] },
    ],
  },
];

Example with no data field:

const tree = arrayToTree(
  [
    { id: "4", parentId: null, custom: "abc" },
    { id: "31", parentId: "4", custom: "12" },
    { id: "1941", parentId: "418", custom: "de" },
    { id: "1", parentId: "418", custom: "ZZZz" },
    { id: "418", parentId: null, custom: "ü" },
  ],
  { dataField: null }
);

Which produces:

[
  {
    id: "4",
    parentId: null,
    custom: "abc",
    children: [{ id: "31", parentId: "4", custom: "12", children: [] }],
  },
  {
    id: "418",
    parentId: null,
    custom: "ü",
    children: [
      { id: "1941", parentId: "418", custom: "de", children: [] },
      { id: "1", parentId: "418", custom: "ZZZz", children: [] },
    ],
  },
];

Example with nested id/parentId properties:

const tree = arrayToTree(
  [
    { num: { id: "4" }, parent: { parentId: null }, custom: "abc" },
    { num: { id: "31" }, parent: { parentId: "4" }, custom: "12" },
  ],
  { id: "num.id", parentId: "parent.parentId" }
);

Which produces:

[
  {
    data: { num: { id: "4" }, parent: { parentId: null }, custom: "abc" },
    children: [
      {
        data: { num: { id: "31" }, parent: { parentId: "4" }, custom: "12" },
        children: [],
      },
    ],
  },
];

TypeScript

This project includes types, just import the module as usual:

import { arrayToTree } from "performant-array-to-tree";

const tree = arrayToTree(array);

Development

yarn version to create a new version npm login npm publish --access public to publish it to npm

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].