Some systems will give you flat arrays with their children and parent. I worked with Notion API and they do that as well. So in this tutorial, I’ll show a simple recursive function that can work to create a deep array with children and parents arrays.

What are Flat arrays?

Flat arrays are arrays that are only 1 level deep. That means that both children and parent items will be on the same level.

To make it easier to display child items under a parent, we would need to have those child items inside of the parent item.

Then, we can use simple for-loops to display them.

Do we need a recursive function?

In the above example, it might not be obvious.

But if you have 100 such items and you don’t know the order in which they’ll be rendered, it might be much harder to do that.

So, creating a recursive function can do just that.

What’s a recursive function? A recursive function will call itself until a condition is met.

Recursive Function

So let’s write it. What do we need?

We need to check for the parent Ids and then check for items that have such parent Id.

If there are items, we will add them to a children attribute.

So, since we are going over the parent Ids and checking for child items, we will always go inside another function call.

This will then check if there are items that have the parent Id set to the Id of the current child, we’re checking.

And it will go like that until we are done with all the items.

The result

The result will be a deep array with only items with parent set to 0 in the level 1.

Conclusion

When you’re dealing with a lot of data that you need to somehow map and relate to each other, recursive functions might help you achieve it much easier.

Have you used recursive functions in some of the solutions you’ve written? Let us know below in the comments.

Become a Sponsor

Posted by Igor Benic

Web Developer who mainly uses WordPress for projects. Working on various project through Codeable & Toptal. Author of several ebooks at https://leanpub.com/u/igorbenic.

Leave a reply

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.