I have a flat array structured as shown below and I am looking to convert it into a nested array with parent-child relationships.
let arr = [
{
id: 4,
parentId:1,
value: 20
},
{
id: 1,
parentId:2,
value: 20
},
{
id: 2,
parentId:1,
value: 20
},
{
id: 3,
parentId:1,
value: 20
},
{
id: 4,
parentId:2,
value: 20
},
]
The desired transformation of this array is illustrated below:
[{
id: 1,
children: [
{
id: 4,
value: 20,
parentId: 1
},
{
id: 2,
value: 20,
parentId: 1
}
...
]
}]
Can someone guide me on how to achieve this using the map() and reduce() functions? Any advice would be greatly appreciated!