Categories
JavaScript Answers

How to Build a Tree Array from Flat Array in JavaScript?

Spread the love

Sometimes, we want to build a tree array from a flattened array in JavaScript.

In this article, we’ll look at how to build a tree array from a flattened array with JavaScript.

Use JavaScript Array Methods and Recursion

We can easily build a tree array from a flattened array with various array methods and recursion.

For instance, we can write:

const comments = [{
  id: 1,
  parentId: null
}, {
  id: 2,
  parentId: 1
}, {
  id: 3,
  parentId: 1
}, {
  id: 4,
  parentId: 2
}, {
  id: 5,
  parentId: 4
}];

const nest = (items, id = null, link = 'parentId') =>
  items
  .filter(item => item[link] === id)
  .map(item => ({
    ...item,
    children: nest(items, item.id)
  }));

console.log(nest(comments))

We have the comments array with the id and parentId properties where the parentId the id of the parent comment.

Then we create the nest function that takes the items array, id and link .

id is the value of parentId .

And link has the property name of the parent ID.

In the function, we call filter to get the child comments with the given ID.

Then call map to map the item with the children array property with the child comments that we get from the nest method.

Therefore, the console log should log:

[
  {
    "id": 1,
    "parentId": null,
    "children": [
      {
        "id": 2,
        "parentId": 1,
        "children": [
          {
            "id": 4,
            "parentId": 2,
            "children": [
              {
                "id": 5,
                "parentId": 4,
                "children": []
              }
            ]
          }
        ]
      },
      {
        "id": 3,
        "parentId": 1,
        "children": []
      }
    ]
  }
]

Conclusion

We can unflatten an array and return a tree array with some array methods and recursion with JavaScript.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *