Movatterモバイル変換


[0]ホーム

URL:


Skip to content
DEV Community
Log in Create account

DEV Community

Daniel Bellmas
Daniel Bellmas

Posted on

     

Build A Tree Array From A Flat Array - Recursion

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:

constentries=[{index:1,parent:0},{index:2,parent:1},{index:3,parent:2},......];
Enter fullscreen modeExit 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:

constarrayToTree=(arr,parent=0)=>arr.filter(item=>item.parent===parent).map(child=>({...child,children:arrayToTree(arr,child.index)}));
Enter fullscreen modeExit fullscreen mode

A quick rundown:

  • We first filter theroot 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:

Top comments(4)

Subscribe
pic
Create template

Templates let you quickly answer FAQs or store snippets for re-use.

Dismiss
CollapseExpand
 
rxliuli profile image
rxliuli
  • Joined
• Edited on• Edited

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 modeExit fullscreen mode
CollapseExpand
 
danielbellmas profile image
Daniel Bellmas
Full-Stack Developer
  • Joined

Cool 😎

CollapseExpand
 
olaf_ranai profile image
Olaf Ranai { dev-it-out }
Software Developer - Coach - Passionate about code and software architecture - with 7 years of experience - VR / AR EnthusiastWanna support me ? https://ko-fi.com/dev_it_out
  • Email
  • Location
    Paris
  • Education
    University of Technology ( Computer Science Degree )
  • Work
    Software Engineer ( Javascript ) at Planity
  • Joined

Nice 👌🏽

CollapseExpand
 
salivity profile image
David Clews
  • Joined

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

Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment'spermalink.

For further actions, you may consider blocking this person and/orreporting abuse

Full-Stack Developer
  • Joined

More fromDaniel Bellmas

DEV Community

We're a place where coders share, stay up-to-date and grow their careers.

Log in Create account

[8]ページ先頭

©2009-2025 Movatter.jp