Skip to content
Advertisement

How to return the children of an array under the parent?

There is an array, inside each element of the array there is a groupId, some elements of the array have children. How to get this kind of output:

JavaScript

Parent category in array:

JavaScript

Children category in array:

JavaScript

I was able to only return parent categories, how to link child categories, in turn I could not figure out how

JavaScript

Advertisement

Answer

I’ve been thinking about for a rather long time and I think I would do it using 2 functions. So here’s the whole code, I also changed the initial array (added a few more items to check functions workability).

First of all, I create an array where groupId is a key. I if the initial array’s key values are important, then we’ll need to do the other logics, but if not (and I suppose they are not matter), then my suggestion is to create array whith subarrays named “ChildrenArray” where we put all children elements.

  1. List item

Check it out:

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