kiltek kiltek - 8 months ago 51
Javascript Question

VisJs - Get number of edges of a specific node

I want to find the number of edges which are connected to a specific node in visjs/javascript.

To illustrate my needs I have made up this example:

<title>Get number of edges of a specific node</title>
<script type="text/javascript" src="/home/altug/Downloads/BTAGViewer/libs/visjs/vis.min.js"></script>
<div id="mynetwork"></div>
<script type="text/javascript">
// create an array with nodes
var nodes = new vis.DataSet([
{id: "A", label: 'label A'},
{id: "B", label: 'label B'},
{id: "C", label: 'label C'},
{id: "D", label: 'label D'},
{id: "E", label: 'label E'}

// create an array with edges
var edges = new vis.DataSet([
{from: "A", to: "C"},
{from: "A", to: "B"},
{from: "B", to: "D"},
{from: "B", to: "E"}

// create a network
var container = document.getElementById('mynetwork');
var data = {
nodes: nodes,
edges: edges
var options = {};
var network = new vis.Network(container, data, options);

var some_id = "B";
var some_node = nodes.get(some_id);

console.log(/*magically retrieve the number of edges for node "B" ---> 3 (for this graph)*/);

I know I could iterate over the edges and count the occurences of the specific node id, like for example:

for(var i = 0; i < edges.get().length; i++){

But isn't there another possibility using vis.js built-in capabilities?


This sort of logic is indeed easy to implement yourself, there is no built-in functionality for it in vis.js. There are a lot of different use cases which would need slightly different algorithms, so we think it's best to leave it up to you and just utilize the flexibility of JavaScript for it.

In your case you could indeed just filter the edges which have the nodeId you're looking for:

function getEdgesOfNode(nodeId) {
  return edges.get().filter(function (edge) {
    return edge.from === nodeId || === nodeId;