0

Having a flat array I would like to map it to a nested one. I saw a lot of answers that flatten a nested array but couldn't found example that do the opposite.

The answer here Build tree array from flat array in javascript is referring to a tree structure logic that is too much complex for my needs. I need just to group it in one level.

For example if my flat array is like:

FlatArray:any[] = [
   {id:1, groupId:1, groupName:'G1', name:'a'}
   {id:2, groupId:1, groupName:'G1', name:'bc'},
   {id:3, groupId:1, groupName:'G1', name:'aa'},
   {id:4, groupId:2, groupName:'G2', name:'bbd'},
   {id:5, groupId:3, groupName:'G3', name:'a1'},
   {id:6, groupId:3, groupName:'G3', name:'ac'},
];

And I would like to get result like:

NestedArray:any[] = [
  {id:1, name:'G1', items:[{id:1,name:'a'},{id:2,name:'bc'},{id:3,name:'aa'}]},
  {id:2, name:'G2', items:[{id:4,name:'bbd'}]},
  {id:3, name:'G3', items:[{id:5,name:'a1'},{id:6,name:'ac'}]}
];

Any help would be appreciated.

ShayD
  • 689
  • 7
  • 17
  • 1
    Does this answer your question? [Build tree array from flat array in javascript](https://stackoverflow.com/questions/18017869/build-tree-array-from-flat-array-in-javascript) – Andreas Aug 03 '21 at 07:44
  • [How much research effort is expected of Stack Overflow users?](https://meta.stackoverflow.com/questions/261592/how-much-research-effort-is-expected-of-stack-overflow-users) – Andreas Aug 03 '21 at 07:44
  • @Andreas As I mentioned, I saw a lot of answers that flatten a nested array but couldn't found example that do the opposite. – ShayD Aug 03 '21 at 07:51

0 Answers0