Build A Tree Array From A Flat Array - Recursion
Daniel Bellmas

Daniel Bellmas @danielbellmas

About: Full-Stack Developer

Joined:
Sep 20, 2021

Build A Tree Array From A Flat Array - Recursion

Publish Date: Apr 1 '22
14 4

I got an assignment to display comments in a recursive way, something like so:

Recursive comments

The data I got from the server was flat, meaning:
every item in the array holds a reference to its parent, like so:



const entries = [
  {
    index: 1,
    parent: 0
  },
  {
    index: 2,
    parent: 1
  },
  {
    index: 3,
    parent: 2
  },
   ...
   ...
   ];


Enter fullscreen mode Exit fullscreen mode

After thinking how to "attack" this problem, I realized
If I want a recursive object, then the easiest solution is a recursive one

Here is the function that converts a flat array to a tree array:



const arrayToTree = (arr, parent = 0) =>
  arr.filter(item => item.parent === parent)
     .map(child => ({ ...child, children: arrayToTree(arr, 
     child.index) }));


Enter fullscreen mode Exit fullscreen mode

A quick rundown:

  • We first filter the root parent's children.
  • Then we do the same to each of the children we just grabbed

My answer to the question on Stack overflow

Here is a codepen if you want to play more with the data ot the solution:


Sources that helped me:

Comments 4 total

  • Olaf Ranai { dev-it-out }
    Olaf Ranai { dev-it-out }Apr 1, 2022

    Nice 👌🏽

  • rxliuli
    rxliuliApr 2, 2022

    I have written something like this and published it as an npm package

    github.com/rxliuli/liuli-tools/blo...

      const [res] = listToTree(
        [
          { id: 3, parent: 1 },
          { id: 4, parent: 1 },
          { id: 1, parent: 0 },
          { id: 2, parent: 0 },
          { id: 5, parent: 2 },
          { id: 6, parent: 2 },
          { id: 0 },
        ],
        {
          id: 'id',
          parentId: 'parent',
          children: 'children',
        },
      )
    
    Enter fullscreen mode Exit fullscreen mode
  • David Clews
    David ClewsJan 31, 2024

    If you are using directories for your structure you could use my solution. It creates a structured object from an array using path and file keys. davidclews.com/article/13.html

Add comment