Home > Enterprise >  JavaScript Detect is Cyclic in an array of objects
JavaScript Detect is Cyclic in an array of objects

Time:08-17

I have an array of Javascript objects as follows

a=[
  {id:1, parentId:2},
  {id:2, parentId:3},
  {id:3, parentId:4},
  {id:4, parentId:1},
  {id:5, parentId:5}
];

I would like to detect in this array if any object refers to itself directly (5->5) or if refers to itself by other parents like 1->2->3->4->1

what is the best way to write it?

PS. There is another question like this one but it is not answered the question. the accepted answer is about a graph and it returns color coding, enter image description here

Any graph traversal algorithm that tracks visited nodes can detect cycles in the graph:

I might suggest converting your list of {id, parentId} tuples into a map, where the keys are the id properties, and the value is the associated parentId (or a list of associated parentID properties, in case the same node can have has multiple parents).

  • Related