Skip to content
Advertisement

Build a tree array (3 dimensional) from a flat array in Typescript/Javascript

I have incoming data in this format:

JavaScript

I want the output to be something like this:

JavaScript

Basically, it is a three dimensional array with first level being the Countrie, second States and third Cities. I have tried the following code:

JavaScript

But the above code works upto second level and does not add cities to states. Could anyone please help me achieve this ?

Thanks a lot!

Advertisement

Answer

You can use a recursive solution:

JavaScript
Advertisement