Component Tree Search
Flatten with reduce + spread
TimeO(n²)SpaceO(n)Suboptimal
Flattens the whole tree (O(n²) from spread/copy at each step), then a separate O(n) filter—so more than two linear passes. Spreading the accumulator and each subtree copies O(n) elements repeatedly; degenerate (list-like) trees give quadratic time. The reduce order can reverse natural tree order unless carefully structured.
Code
1interface ComponentNode {
2 id: string
3 type: string
4 children?: ComponentNode[]
5}
6
7const tree: ComponentNode = {
8 id: "root",
9 type: "Page",
10 children: [
11 {
12 id: "header",
13 type: "Header",
14 children: [
15 { id: "logo", type: "Image" },
16 { id: "nav", type: "Nav" }
17 ]
18 },
19 {
20 id: "content",
21 type: "Section",
22 children: [
23 { id: "hero", type: "Image" },
24 { id: "cta", type: "Button" }
25 ]
26 }
27 ]
28}
29
30function flatten(tree: ComponentNode): ComponentNode[] {
31 return (tree.children || []).reduce(
32 (acc, c) => [...acc, ...flatten(c)],
33 [tree]
34 ) || []
35}
36
37
38function findComponentsByType(
39 tree: ComponentNode,
40 targetType: string
41): ComponentNode[] {
42 return flatten(tree).filter(node => node.type === targetType)
43}
44
45console.log(findComponentsByType(tree, "Button"))
46Animation
Component tree
Pageroot
Headerheader
Imagelogo
Navnav
Sectioncontent
Imagehero
Buttoncta
Result (traversal order)
—
—
Speed: