AniUI Academy
easy+150 XPPractice

Flatten a comment tree for rendering

A virtualised list can only render a flat array, but comment threads and folder trees are nested. The usual fix is to flatten the tree into rows, each carrying the indent level it should be drawn at.

Implement flattenTree(nodes). nodes is an array of root nodes, each shaped { id, children } where children is an array of nodes and may be missing. Return a flat array of objects, each with exactly two properties: id (copied from the node) and depth (a number, 0 for a root). Order the result depth-first in pre-order: a node comes immediately before its own descendants, and siblings keep their array order. An empty input array returns an empty array.

What it has to do

  • Each entry has exactly two properties, id and depth.
  • Roots have depth 0 and each level of nesting adds 1.
  • A node appears immediately before its descendants, and siblings keep their order.
  • Return an empty array for an empty input.
  • Treat a missing children property as no children.

Your workspace

Try it yourself
Loading playground...

Ready to check it?

5 tests run against your code, right here in your browser. Sign in to claim the XP when you pass.

AI Crack & Solution Assist

Stuck? Get instant AI hints or break down the optimal solution.

Stuck? The javascript course covers everything this challenge needs.