function findNodeWithMostChildren(data, level = 0, index = 0) {
if (!data.children || data.children.length === 0) {
return { level, index };
}
let maxChildren = 0;
let maxChildIndex = 0;
for (let i = 0; i < data.children.length; i++) {
const child = data.children[i];
if (child.children && child.children.length > maxChildren) {
maxChildren = child.children.length;
maxChildIndex = i;
}
}
if (maxChildren > 0) {
return findNodeWithMostChildren(data.children[maxChildIndex], level + 1, maxChildIndex);
} else {
return { level, index };
}
}
const demoData = {
id: '1',
name: '1',
children: [
{ id: '1-1', name: '1-1' },
{ id: '1-1', name: '1-1' },
{
id: '1-2',
name: '1-2',
children: [
{ id: '1-2-1', name: '1-2-1' },
{ id: '1-2-2', name: '1-2-2' },
{ id: '1-2-3', name: '1-2-3' },
],
},
{
id: '1-3',
name: '1-3',
children: [{ id: '1-3-1', name: '1-3-1' }],
},
],
};
const result = findNodeWithMostChildren(demoData);
console.log(`Level: ${result.level}, Index: ${result.index}`);
console