Codiqo

Learn JavaScript · lesson 52 of 60 · about 10 minutes

Project: Nested Menu

Count and print a menu whose sections can hold more sections, to any depth.

What you'll learn

  • Recognise data that contains itself
  • Recurse into child arrays
  • Pass the depth down to indent output

Sam's site map

Sam's site has grown: an About me page, a Revision section with Flashcards and a Notes section inside it, and a Projects section. That's a map with sections inside sections, the same shape as the café menu below. The page shows the whole map with each level indented two spaces further in, and sums it up: 6 pages, up to 3 levels deep. Recursion handles any depth, so the page keeps working however Sam reorganises the site.

Data inside data

A café menu has sections, and a section can hold dishes and smaller sections, like Drinks → Hot → Tea.

Each item is an object: { name: "Tea" } is a dish, and { name: "Hot", items: [...] } is a section. You can't know in advance how deep it goes, which is exactly when recursion helps.

Counting every dish

const menu = { name: "Menu", items: [
  { name: "Toast" },
  { name: "Drinks", items: [
    { name: "Juice" },
    { name: "Hot", items: [{ name: "Tea" }, { name: "Cocoa" }] },
  ] },
] };

function countDishes(item) {
  if (!item.items) return 1;
  let total = 0;
  for (const child of item.items) total += countDishes(child);
  return total;
}

console.log(countDishes(menu));

Output

4

Printing with indents

Give the function a second parameter, depth, and pass depth + 1 to each child. " ".repeat(depth) then indents every line by its level.

Showing the shape

const menu = { name: "Drinks", items: [
  { name: "Juice" },
  { name: "Hot", items: [{ name: "Tea" }] },
] };

function show(item, depth) {
  console.log("  ".repeat(depth) + item.name);
  for (const child of item.items ?? []) show(child, depth + 1);
}

show(menu, 0);

Output

Drinks
  Juice
  Hot
    Tea

Lines for the page

On Sam's page the map goes into one element, so instead of logging each line, the function returns an array of lines: its own name first, then every line its children give back, spread in with .... join("\n") puts them together, and a <pre> element keeps the line breaks and the spaces.

A map in one element

const notes = { name: "Notes", items: [{ name: "Arrays" }, { name: "Loops" }] };

function lines(item, depth) {
  const out = ["  ".repeat(depth) + item.name];
  for (const child of item.items ?? []) out.push(...lines(child, depth + 1));
  return out;
}

document.querySelector("#tree").textContent = lines(notes, 0).join("\n");
console.log(document.querySelector("#tree").textContent);

Output

Notes
  Arrays
  Loops

Tip

item.items ?? [] gives an empty array for dishes, so the loop simply doesn't run for them.

Now try it yourself

This lesson is free in Codiqo, with 9 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.