0

I have a nested structure as below:

       arr[3].title="a3";        
       arr[3].nextArr=[];
       arr[2].title="a2"; 
       arr[2].nextArr=arr[3];
       arr[1].title="a1"; 
       arr[1].nextArr=arr[2];
       arr[0].title="a0"; 
       arr[0].nextArr=arr[1];

like here!:

|_
  |_
    |_

As you see, I have one array called arr with four members.

How can I make four separated arrays from arr?

arrayOne=[{title:"a1"},{nextArr:[]}];    
arraytwo=[{title:"a2"},{nextArr:[]}];
.
.
.

Update: I need this converts in my AngularJS controller.js. I get a response from server which contains an array as above. And I have to make it flat. The count of inner arrays are not constant. I didn't mention that because I didn't know the algorithm. But, according to answers, it seems Itt was better if I explained it more.

Result = {arr[title:"a0",nextArr:{title:"a1",nextArr:{title:"a2",nextArr:{......}}}]};
Elnaz
  • 2,854
  • 3
  • 29
  • 41
  • `arrayOne=arr[1]; arraytwo=arr[2];` – Logman Jun 08 '16 at 14:53
  • 2
    It looks like a `"a0" -> "a1" -> "a2" -> []` single linked list. But what is the type of `nextArray` field? How can it point both to `[]` and to structure of two fields `title, nextArray`? If it's a list, list traversing algorithms would work. – Andrey Moiseev Jun 08 '16 at 15:04
  • All of arrays have similar type.in last one, the next array is an empty array. I updated the question. – Elnaz Jun 08 '16 at 18:02

1 Answers1

0

You can use yield to create an enumerator that recursively walks the hierarchy:

public IEnumerable<{class}> Flatten({class}[] data)
{
    foreach({class} parent in data)
    {
        yield return parent;

        foreach({class} child in flatten(parent.nextArr))
            yield return child;
    }
}
D Stanley
  • 149,601
  • 11
  • 178
  • 240