I'm trying to run recursive-ly in an array in a react aplication, I got it this way and I want to improve my function to run the array:
my Array:
tree: [
{
key: 0 ,
name: 'menu 1',
children: [
{
key: 1,
name: 'submenu 1 - 1'
},{
key: 2,
name: 'submenu 1 - 2'
}
]
},{
key: 3 ,
name: 'menu 2',
children: [
{
key: 4,
name: 'submenu 2 - 1'
},{
key: 5,
name: 'submenu 2 - 2'
}
]
}
]
And I run this Array this way:
const findInArrayTree = (tree, search) =>{
let it,
result
for (it = 0; it < tree.length; it += 1) {
result = findNode(tree[it], search);
if(result !== false){
return result;
}
}
return result;
};
const findNode = (currentNode, search) => {
let i,
currentChild,
result;
if (search == currentNode.key) {
return currentNode;
} else {
// Use a for loop instead of forEach to avoid nested functions
// Otherwise "return" will not work properly
if(currentNode.children){
for (i = 0; i < currentNode.children.length; i += 1) {
currentChild = currentNode.children[i];
// Search in the current child
result = findNode(currentChild, search);
// Return the result if the node has been found
if (result !== false) {
return result;
}
}
}
// The node has not been found and we have no more options
return false;
}
};
Someone can help-me to improve this? I want to do this run in one function only, but my brain is broken alredy..