I have a JS array that looks like this:
const arr = [
{
i: "tooltip_119",
children: [
{
i: "text_345",
children: []
},
{
i: "wraper_375",
children: [
{
i: "grid_15",
children: []
}
]
}
]
},
{
i: "chart_123",
children: []
},
{
i: "graph_467",
children: []
},
]
The idea is that such an array can potentially have an infinite number of nestings. And I need a function that, taking the i
parameter of some element, will return the i
parameter of its parent (or 0 if the element is at the root and has no parents). An example of how such a function works:
console.log(findParent(arr, "grid_15")) // returns "wraper_375"
I wrote a function like this:
export function findParent(arr, i) { // this func has a bug on deep levels
for (let j = 0; j < arr.length; j++) {
const element = arr[j];
if (element.children && element.children.length > 0) {
const childElement = element.children.find((e) => e.i === i);
if (childElement) {
return element.i;
} else {
const parentElement = findParent(element.children, i);
if (parentElement) {
return parentElement.i;
}
}
}
}
return 0;
}
The problem is that my function doesn’t work at deeper levels of nesting. I would be grateful for help