Search code examples
datasetvis.jsvis.js-network

In the vis.js library, how do I get the max value in the "id" field?


I'm discovering vis.js, especially the network module.

I need to get the max value of the "id" field of my nodes dataset:

var nodes = new vis.DataSet([ {id: 1, label: "Node 1"}, {id: 2, label: "Node 2"}, {id: 3, label: "Node 3"}]);

The best I've been able to do so far is using a forEach loop:

var max=0;
nodes.forEach(function(el){j=parseInt(el.id);if(j!=NaN && j>max){max=j;}});
console.log("max: ", max);

It seems to me it can't be THE way to do this. I saw a max(field) method documented in the doc for vis' DataSet (https://visjs.github.io/vis-data/data/dataset.html):

max(field) [Object|null] Find the item with maximum value of specified field. Returns null if no item is found.

But as stupid as i may sound, I just can't get it to work. I tried :

console.log("max: ", nodes.max('id'));
console.log("max: ", nodes.max(node => node.id));
console.log("max: ", nodes.max(node => node['id']));

How can I simply get the max value of the field 'id' of all entries of a DataSet?

[Edit] The ID's in the example here above are numeric ({id: 1, ...}).
In my case, they were strings ({id: '1', ...}), and exactly that seemed to be the problem.


Solution

  • After loads of lost time, I finally figured out that max() works perfectly with numeric IDs.
    My first thought was then: Reading the doc could have saved me hours...

    ...But checking https://visjs.github.io/vis-network/docs/network/nodes.html , it explicitely defines ID as a string:

    [name:] id [type:] String [default:] undefined [description:] The id of the node. The id is mandatory for nodes and they have to be unique. This should obviously be set per node, not globally.

    So beware: it's supposed to be a string, but if it's a string, some features don't work.
    If I'm still missing something, I'd be happy to read your comments.