I currently have a Javascript array of objects like so:
myArray = [
{
id: 'top-id1',
title: 'title1',
subElements: [
{
id: 'id2',
title: 'title2',
subElements: [
{
id: 'id3',
title: 'title2',
subElements: [
...
]
}
]
},
{
id: 'id4',
title: 'title4',
},
...
]
},
{
id: 'top-id5',
title: 'title5',
subElements: [
...
]
},
...
];
This array can technically be infinitely long and infinitely deep (through the subElements), but in practice it will only have 4 max objects at the top level and go 4 levels deep max so performance and runtime isn't a huge concern.
What I'm trying to find: Given any id, I need to return the id of the top level object that contains the first id. So if I'm given 'id3', I need to return 'top-id1'. And if I'm given 'top-id5', I also need to return 'top-id5'. For what it matters, this is in the context of a React application. Can someone help me figure out an algorithm to do so?