# Why does this topological sort miss some nodes with only incoming edges?

**URL:** <https://forum.kirupa.com/t/why-does-this-topological-sort-miss-some-nodes-with-only-incoming-edges/679906>\
**Category:** web dev\
**Created:** [April 3, 2026, 4:00am UTC](https://forum.kirupa.com/t/why-does-this-topological-sort-miss-some-nodes-with-only-incoming-edges/679906 "2026-04-03T04:00:11Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![Yoshiii](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/yoshiii/32/31156_2.png) [@Yoshiii](https://forum.kirupa.com/u/Yoshiii)\
**Post date:** [April 3, 2026, 4:00am UTC](https://forum.kirupa.com/t/why-does-this-topological-sort-miss-some-nodes-with-only-incoming-edges/679906/1 "2026-04-03T04:00:11Z")

</div>

I’m implementing Kahn’s algorithm, but tasks that only appear as dependencies never show up in the result. I expected all nodes in the graph to be included. What am I initializing incorrectly?

```js
function topo(edges) {
  const indeg = new Map(), g = new Map();
  for (const [a, b] of edges) {
    if (!g.has(a)) g.set(a, []);
    g.get(a).push(b);
    indeg.set(b, (indeg.get(b) || 0) + 1);
    if (!indeg.has(a)) indeg.set(a, 0);
  }
  const q = [...[...indeg].filter(([,d]) => d === 0).map(([n]) => n)];
  const out = [];
  while (q.length) for (const n of g.get(q.shift()) || []) if (indeg.set(n, indeg.get(n)-1).get(n) === 0) q.push(n), out.push(n);
  return out;
}

```

Yoshiii

---

<div class="post-metadata">

**Author:** ![MechaPrime](https://yyz1.discourse-cdn.com/flex011/user_avatar/forum.kirupa.com/mechaprime/32/31154_2.png) [@MechaPrime](https://forum.kirupa.com/u/MechaPrime)\
**Post date:** [April 3, 2026, 4:07am UTC](https://forum.kirupa.com/t/why-does-this-topological-sort-miss-some-nodes-with-only-incoming-edges/679906/2 "2026-04-03T04:07:05Z")

</div>

You’re not missing their initialization.

MechaPrime
