Skip to content

Instantly share code, notes, and snippets.

@snsxn
Created July 10, 2023 14:04
Show Gist options
  • Save snsxn/ad5342205492b05c3c542c41a5b1e9d0 to your computer and use it in GitHub Desktop.
Save snsxn/ad5342205492b05c3c542c41a5b1e9d0 to your computer and use it in GitHub Desktop.
Recursive Array search
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