I am dealing with a diverse array of objects, each structured in a specific way:
data = [
{
content: {
...,
depth: 1
},
subContent: []
},
{
content: {
...,
depth: 2
},
subContent: []
},
{
content: {
...,
depth: 3
},
subContent: []
},{
content: {
...,
depth: 2
},
subContent: []
},
{
content: {
...,
depth: 1
},
subContent: []
},
]
The desired structure for these objects is as follows:
result = [
{
content: {
...,
depth: 1
},
subContent: [
{
content: {
...,
depth: 2
},
subContent: [
{
content: {
...,
depth: 3
},
subContent: []
}
]
},
{
content: {
...,
depth: 2
},
subContent: []
},
],
{
content: {
...,
depth: 1
},
subContent: []
},
},
]
To achieve this structure, I've created a loop that iterates through the array and arranges higher depth objects within lower ones. If they are not on the same depth level, the object will be placed at the appropriate nested level based on its depth.
for (let i = arr.length-1; i > 0; i--) {
if (arr[i].content.depth === arr[i-1].content.depth + 1) {
arr[i-1].subContent.push(arr[i]);
arr.splice(i, 1);
} else {
let index = this.findNextLowerIndex(arr[i].content.depth, arr);
// console.log(index);
if (arr[index]) {
arr[index].subContent.push(arr[i]);
arr.splice(i, 1);
}
}
}
findNextLowerIndex(depth: number, arr: any[]): number {
let findIndex = depth - 1;
for (let i = arr.length-1; i > 0; i--) {
if (arr[i].content.depth === findIndex) {
return i;
}
}
}
This approach works well for most scenarios, however, it struggles when dealing with multiple layers of subContent. For instance, when the array depths are arranged like 4, 3, 4, 3, 2, 1, the nesting might not be optimal. It can lead to missing relationships between certain layers of subContent.
If you have any suggestions or ideas on how to improve this nesting logic, feel free to share!