introductionWe often encounter tree-like data structures, such as organizational hierarchies, provinces, cities, counties, or animal and plant classifications. The following is an example of a tree structure: In practical applications, it is common to store this information as the following structure, especially when there is a one-to-many parent/child node relationship: const data = [ { id: 56, parentId: 62 }, { id: 81, parentId: 80 }, { id: 74, parentId: null }, { id: 76, parentId: 80 }, { id: 63, parentId: 62 }, { id: 80, parentId: 86 }, { id: 87, parentId: 86 }, { id: 62, parentId: 74 }, { id: 86, parentId: 74 }, ]; So, how do we convert this object array format into a hierarchical tree format? In fact, using the characteristics of JavaScript object references, it is very simple to implement. It can be done in O(n) time without recursion. the term For the sake of convenience, let us first define a few terms. We call each element in the array (that is, each circle in the tree diagram) a "node". A node can be the "parent node" of multiple nodes, or the "child node" of a certain node. In the above figure, node 86 is the “parent node” of node 80 and node 87, and node 86 is the child node of node 74. The topmost node of the tree is called the "root node". IdeasTo construct the tree structure, we need:
We can see that references are stored in the object tree, which is why we can complete this task in O(n) time! Establish ID-array index mapping relationshipAlthough it is not required, this mapping relationship can help us quickly find the location of the element and facilitate finding the reference to the parent element. const idMapping = data.reduce((acc, el, i) => { acc[el.id] = i; return acc; }, {}); The mapping results are as follows, and you will see how useful it is later:
Constructing a tree structureNow we start constructing this tree structure. Iterate through the array of objects, find the parent object of each element, and then add a reference to the element. Now you should see how convenient this idMapping is for locating elements (constant time). let root; data.forEach(el => { // Determine the root node if (el.parentId === null) { root = el; return; } // Use the mapping table to find the parent element const parentEl = data[idMapping[el.parentId]]; // Add the current element to the `children` array of the parent element parentEl.children = [...(parentEl.children || []), el]; }); Done! Use console.log to print root and see: console.log(root);
principleWhy is this possible? This is because each element in the data array is a reference to an object in memory, the el variable in the forEach loop actually points to an object in memory, and parentEl also references an object. If an object in memory references a children array, these child elements can also reference their own child element arrays. These associations are all completed through references. SummarizeObject reference is one of the most fundamental concepts in JavaScript and requires more learning and understanding. Once you truly understand this concept, you can avoid tricky bugs and come up with relatively simple solutions to seemingly complex problems. The above is a brief discussion of the details of an efficient algorithm for constructing tree structures in JavaScript. For more information on JavaScript algorithms for constructing tree structures, please pay attention to other related articles on 123WORDPRESS.COM! You may also be interested in:
|
<<: Detailed installation tutorial of mysql-8.0.11-winx64.zip
>>: Solution to Linux CentOS 6.5 ifconfig cannot query IP
Recently I was looking at how Docker allows conta...
This article shares a simple HTML shopping quanti...
Table of contents Scenario Analysis Development S...
<br />The frame structure allows several web...
Table of contents Preface Reference Comparison Ma...
Wildcard categories: %Percent wildcard: indicates...
Table of contents Introduction Traditional transi...
The purpose of using HTML to mark up content is t...
Table of contents Written in front Two-way encryp...
Table of contents 1. What is an Operating System ...
Table of contents Preface Check Constraints Creat...
The happiest thing that happens in a production e...
1. Optimize Nginx concurrency [root@proxy ~]# ab ...
Table of contents Use of Vue mixin Data access in...
Table of contents 1. Declare a function 2. Callin...