Practical Example of Building tree array from a flat array in JavaScript
This example uses a Loop and Object References to build a tree view of comments from the “flatComments” array data and then render it in web view using the renderCommentsTree() function which interacts with HTML Code. Use CSS for a better look.
Example: Practical Example of Building a tree array from a flat array in JavaScript.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, initial-scale=1.0">
<title>Comments Tree</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<h3>Practical Example of Building tree
array from flat array in JavaScript
</h3>
<div id="comments-container"></div>
<script src="script.js"></script>
</body>
</html>
/* style.css*/
body {
font-family: Arial, sans-serif;
max-width: 800px;
margin: 0 auto;
padding: 20px;
background-color: #f2f2f2;
color: #333;
}
h3 {
text-align: center;
color: #2c6e49;
}
.comment {
border: 1px solid #c5d6c7;
border-radius: 4px;
padding: 10px;
margin-bottom: 10px;
background-color: #e8f5e9;
}
.comment-author {
font-weight: bold;
margin-bottom: 5px;
color: #2c6e49;
}
.comment-content {
margin-bottom: 10px;
}
.replies {
margin-left: 20px;
}
// script.js
// Flat array of comments
const flatComments = [
{ id: 1, parentId: null, author: 'Jeetu',
content: 'This is a great article!' },
{ id: 2, parentId: 1, author: 'Mihika',
content: 'I agree, very informative.' },
{ id: 3, parentId: 1, author: 'Disha',
content: 'I was wondering if you could provide more examples on the topic?' },
{ id: 4, parentId: 3, author: 'Shravan',
content: 'Ohhk!!' },
{ id: 6, parentId: 4, author: 'Shravan',
content: 'I added more Examples!!' },
{ id: 7, parentId: 6, author: 'Disha',
content: 'Great, thanks!' }
];
// Build the tree array
function buildCommentsTree(flatComments) {
const nodeMap = {};
const result = [];
// Create a reference object
flatComments.forEach(comment => {
nodeMap[comment.id] =
{ ...comment, children: [] };
});
// Build the tree array
flatComments.forEach(comment => {
const node = nodeMap[comment.id];
if (comment.parentId !== null) {
nodeMap[comment.parentId]
.children.push(node);
} else {
result.push(node);
}
});
return result;
}
const commentsTree = buildCommentsTree(flatComments);
// Render the comments tree in the webview
function renderCommentsTree(commentsTree) {
const commentsContainer =
document.getElementById('comments-container');
function renderComment(comment, level = 0) {
const commentElement =
document.createElement('div');
commentElement.classList.add('comment');
commentElement.style.marginLeft = `${level * 20}px`;
commentElement.innerHTML = `
<div class="comment-author">${comment.author}</div>
<div class="comment-content">${comment.content}</div>
<div class="replies"></div>`;
const repliesContainer =
commentElement.querySelector('.replies');
comment.children.forEach(child => {
repliesContainer
.appendChild(renderComment(child, level + 1));
});
return commentElement;
}
commentsTree.forEach(comment => {
commentsContainer.appendChild(renderComment(comment));
});
}
renderCommentsTree(commentsTree);
Output:
Build Tree Array from Flat Array in JavaScript
To convert a flat array of comments into a tree-like structure using JavaScript. This technique is particularly useful when you need to render nested comments or any other hierarchical data in your web application. We will write a function called buildCommentsTree that takes the flat array of comments as input and returns a tree-like array of comments.
Below are the approaches to build a tree array from a flat array in javascript:
Table of Content
- Using a Loop and Object References
- Using Array.prototype.reduce()
- Using Recursion