Skip to content
Advertisement

How to convert flat data structure to tree structure in JavaScript using recursion

I want to create a tree from the data provided using recursion. I am also trying to get the tree to pass an npm test, but when I run the test, it is failing. I am getting a tree, but it looks different than the one it is supposed to look like.

Here is the code (with instructions in a comment):

JavaScript

Advertisement

Answer

Your reduce should produce a plain object, not an array — there is no array in your desired output. Also, your code produces a property child, but there is no such property in your desired output. It seems like code that is specifically intended for a different output structure.

Here is the adapted reduce call:

JavaScript

It should be noted that this is not an efficient way of doing it. It needs several passes of the whole array, giving this a quadratic time complexity, while an iterative method can do this with a linear time complexity.

User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement