Dev Helpers
← Back

Collect labels depth first

Collect labels depth first using TypeScript.

Open this example in the interactive library

Source code

type Tree = { label: string; children: Tree[] };
const root: Tree = {
  label: "src",
  children: [
    { label: "app", children: [{ label: "ui", children: [] }] },
    { label: "lib", children: [] },
  ],
};
console.log(
  (() => {
    function labels(t: Tree): string[] {
      return [t.label, ...t.children.flatMap(labels)];
    }
    return labels(root);
  })(),
);

Sample output

[ 'src', 'app', 'ui', 'lib' ]