Last active
April 2, 2020 12:51
-
-
Save deepakshrma/7eb0d78aeb4889938a2424f7d681760a to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
const tree = { | |
name: "A", | |
children: [ | |
{ name: "A-1", children: [{ name: "A-1-A" }, { name: "A-1-B" }] }, | |
{ | |
name: "B-1", | |
children: [ | |
{ name: "B-1-A", children: [{ name: "B-11-A" }, { name: "B-11-B" }] }, | |
{ name: "B-1-B" } | |
] | |
} | |
] | |
}; | |
const searchFn = (tree, name) => { | |
let result = null; | |
if (typeof tree !== "object") return result; | |
if (tree.name === name) return tree; | |
if (tree.children && tree.children.length) { | |
tree.children.some(data => (result = searchFn(data, name))); | |
} | |
return result; | |
}; | |
console.log(searchFn(tree, "A-1-A")); | |
console.log(searchFn(tree, "A-1")); | |
console.log(searchFn(tree, "")); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment