Build a comment tree from a flat list and render recursively

This problem asks you to render nested comments in React by rendering lists recursively. You are given a flat array of posts and comments. Each item in the array represents either a top-level post or a comment on a post (or another comment). Each object has the following properties:
id (number): A unique identifier for the post or comment.text (string): The content of the post or comment.replyTo (number, optional): The id of the post or comment that this comment is replying to. If absent, the item is a top-level post.Your task is to convert this flat array into a nested tree structure that represents the parent-child relationships between posts and comments, and render this structure recursively as an indented list (as a React component, or with vanilla JavaScript into the #comments element).
replies array containing its direct children.<li>). Render its replies in a nested list (<ul>) inside that same <li>. Don’t render an empty nested list for items without replies.
posts: Array<{
id: number,
text: string,
replyTo?: number
}>
Array<{
id: number,
text: string,
replyTo?: number,
replies: Array<...>
}>
Input:
[
{ id: 1, text: "This is a post 1" },
{ id: 2, replyTo: 1, text: "This is a comment, child to post 1" },
{ id: 3, replyTo: 2, text: "This is a comment, child to comment 2" },
{ id: 4, replyTo: 1, text: "This is a comment, child to post 1" },
{ id: 5, text: "This is a post 2" }
]
Output (tree structure):
[
{
id: 1,
text: "This is a post 1",
replies: [
{
id: 2,
replyTo: 1,
text: "This is a comment, child to post 1",
replies: [
{
id: 3,
replyTo: 2,
text: "This is a comment, child to comment 2",
replies: []
}
]
},
{
id: 4,
replyTo: 1,
text: "This is a comment, child to post 1",
replies: []
}
]
},
{
id: 5,
text: "This is a post 2",
replies: []
}
]
Explanation:
- Posts and comments are arranged in a tree structure, where each comment is nested under its parent based on the replyTo field. - Comments can be nested to any depth. - Only items without a replyTo field appear at the top level of the result.
The tests render the example data from the starter code and read the list you produce. You don’t need test ids or specific class names. They only check that:
<li>, in tree order (a reply comes right after its parent, before the parent’s next sibling).<li>.<li> sits in a nested list inside its parent’s <li> (comment 3 is two levels deep).