I am facing a challenge with a list of elements that have unique IDs and parent IDs. My goal is to identify any loops in this hierarchical structure and pinpoint the ID that initiates the loop.
list = [
{
id: '1',
parent: '2'
},
{
id: '2',
parent: '3'
},
{
id: '3',
parent: '4'
},
{
//The loop starts at this ID
id: '4',
parent: '1'
}
]
I have attempted to construct a tree using the given list, which functions correctly under normal circumstances but fails when a loop is present:
function treeify(list, idAttr, parentAttr, childrenAttr) {
if (!idAttr) idAttr = 'id';
if (!parentAttr) parentAttr = 'parent';
if (!childrenAttr) childrenAttr = 'children';
var treeList = [];
var lookup = {};
list.forEach(function(obj) {
lookup[obj[idAttr]] = obj;
obj[childrenAttr] = [];
});
list.forEach(function(obj) {
if (obj[parentAttr] != null) {
lookup[obj[parentAttr]][childrenAttr].push(obj);
} else {
treeList.push(obj);
}
});
return treeList;
};
Despite my efforts, I have been unsuccessful in detecting loop occurrence within the hierarchy.
My objective is to not only identify the loop but also retrieve the ID of the element responsible for the loop, enabling me to rectify the underlying data structure.