Skip to content
Advertisement

Build nodes like array from flat array

I’m trying to restructure the following javascript flat array without parent_id.

I want to have a structure for React Tree Table like example in this page: https://www.robinwieruch.de/react-tree-table/

JavaScript

I want a another array that dynamically group according to this array’s keys:

JavaScript

I want to have a structure like this and pass an another array to group. Ideally a want sum the hours in each group

JavaScript

I have already make this code:

JavaScript

But I don’t have sums and all informations in the last children.

Advertisement

Answer

You could use a recursive function. First create a map keyed by the data for the first key, associating a group object with nodes and hours properties, and then populate the nodes and sum up the hours.

Then repeat in recursion for those (smaller) node arrays. The recursion stops when there are no more keys to group by.

Here is an implementation:

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