Created
July 10, 2023 14:04
-
-
Save snsxn/ad5342205492b05c3c542c41a5b1e9d0 to your computer and use it in GitHub Desktop.
Recursive Array search
This file contains 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 array = [ | |
{ id: 1 }, | |
{ id: 2 }, | |
{ id: 3 }, | |
{ id: 4, children: [ | |
{ id: 6 }, | |
{ id: 7, children: [ | |
{ id: 8 }, | |
{ id: 9 } | |
] | |
} | |
]}, | |
{ id: 5 } | |
]; | |
function recursiveFind(data, id) { | |
function iter(a) { | |
if (a.id === id) { | |
result = a; | |
return true; | |
} | |
return Array.isArray(a.children) && a.children.some(iter); | |
} | |
var result; | |
data.some(iter); | |
return result | |
} | |
// recursiveFind(array, 8) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment