Search code examples
cytoscape-web

Is there a direct way to get a node's neighbors?


Is there a direct way to get all network neighbors of a node n0 in Cytoscape.js?

The best solution that has occurred to me so far is to get all edges where n0 is the source and all edges where n0 is the target -- and then look at those edges' targets and sources, respectively.

Is there a more convenient way, say something like a function cy.nodes("#n0").neighbors()?

The reason I need this is that I would like to implement a function that removes a node n0, but also other nodes that have no edges after removing n0 should be removed. Ideas on this will be appreciated.

Thanks!


Solution

  • node.neighborhood() also includes edges, so you can use node.neighborhood('node') or any other selector if you want to filter the neighbourhood.

    Edit: You can also use degree to do what you want.

    var otherNodesToDelete = node.neighborhood('node{degree = 1}');

    Or you can do node.remove() and then do cy.$('node{degree = 0}') to look for disconnected nodes.