Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

159
Views
Creating breadcrumbs from a link tree with DFS in JavaScript

I am struggling to write a DFS algorithm in JavaScript to create breadcrumbs for a link tree. Given the below input of linkItems and expected output that I am console logging, I've only gotten the first couple of levels to work. What am I missing?

const linkItems = {
  id: "a",
  links: [
    {
      id: "b",
      links: [
        {
          id: "c"
        }
      ]
    },
    {
      id: "d",
      links:  [{
        id: "e",
        links: [
          {
            id: "f"
          }
        ]
      },
        {
          id: "g"
        }]
    }
  ]
};

const flattenLinkItems = (id, root) => {
  if (!root) return null;

  let node = null;
  let acc = [];
  let q = [];
  q.push(root);
  while (q.length > 0) {
    node = q.shift();
    if (node.links) {
      const { links, ...item } = node;
      acc.push(item.id)
      if (item.id === id) {
        q = [];
        return acc
      }
      q = links;
    } else {
      acc.push(node.id)
      if (node.id === id) {
        q = [];
        return acc
      } else {

      }
    }
  }
  return acc;
}


let findThis = []
// given id of...
// ... c will return ['a','b','c']
  findThis = flattenLinkItems("c", linkItems);
  console.log("given c", findThis);

// d will return ['a','d']
  findThis = flattenLinkItems("d", linkItems);
  console.log("given d", findThis);

// f will return ['a','d','e','f']
  findThis = flattenLinkItems("f", linkItems);
  console.log("given f", findThis);

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!