Search code examples
javascriptchap-links-libraryvis.js

Cannot get vis.js last or first selected network node


I am playing with vis.js and have worked out how to get an array of all the currently selected nodes.

var TempNodes = network.getSelectedNodes();

My problem is that the getSelectedNodes() array is returned with all the nodes id's in numeric order from lowest to highest...There doesn't seem to be a way to tell what the last selected node id was or what the first selected node id was. I can only tell which node id's were selected.

Does anyone know a way to be able to find out from the getSelectedNodes array, what was the first or last selected node id ?


Solution

  • Using the concepts tucuxi put forward, I did come up with some working code to achieve this. Although tucuxi's code did not work 'straight out of the box' his idea was sound and he deserves credit for it.

    Here is the code that eventually worked for me

     var PreviouslySelectedNodes = [];
        var SelectedNodesInOrder = [];
    
        network.on('select', function (properties) {      
    
          // itterate through each visjs selected nodes and see if any value is not present in our current ordered list
          // If it's not already present, push it to the top of our ordered list
          var SelectedNodeIDs = network.getSelection().nodes // First get all the visjs selected nodes
    
          // If only one Node is currently selected, then empty the SelectedNodesInOrder array ready for a new set
          if(SelectedNodeIDs.length == 1){
              SelectedNodesInOrder = [];
          }
    
          // Cycle through all current selected visjs nodes
          for(var t = 0; t <= SelectedNodeIDs.length; t++){
    
              // cycle through all currently selected ordered nodes in our ordered array
              var found = false; flag the default as this node not already in our ordered list
              for(var y = 0; y <= SelectedNodesInOrder.length; y++){
                    if(SelectedNodesInOrder[y] == SelectedNodeIDs[t]){ // This node already exists in our ordered list
                        found = true;
                    }         
              }
    
              // If the current visjs selected node doesn't already exist in the SelectedNodesInOrder, then add it
              if(found === false){
                    SelectedNodesInOrder.push(SelectedNodeIDs[t]);
              }
    
          }
    
        console.log(SelectedNodesInOrder); // test by dumping our ordered array list to the console
    
        });