Link JSON filters to specific JSON nodes on the map

I have data representing nodes and links for a force directed graph. The links can have different numbers of connections between them, such as one, two, or three links:

{"nodes": [{"id": "Michael Scott", "type": "boss"}
          ,{"id": "Jim Halpert", "type": "employee"}
          ,{"id": "Pam Beasley", "type": "employee"}
          ,{"id": "Kevin Malone", "type": "employee"}
          ,{"id": "Angela", "type": "employee"}
          ,{"id": "Dwight Schrute", "type": "employee"}]
,"links": [{"source": "Michael Scott", "target": "Jim Halpert", "num": 1}
          ,{"source": "Pam Beasley", "target": "Kevin Malone", "num": 2}
          ,{"source": "Pam Beasley", "target": "Kevin Malone", "num": 2}
          ,{"source": "Angela", "target": "Dwight Schrute", "num": 3}
          ,{"source": "Angela", "target": "Dwight Schrute", "num": 3}
          ,{"source": "Angela", "target": "Dwight Schrute", "num": 3}]
}

There is a dropdown menu that will be used to filter the nodes and links displayed on the d3 force-directed graph based on the number of connections (num). I am currently working on the JavaScript code to achieve this filtering:

var dropdown = d3.select("#selectLinkNumber")
var change = function() {
d3.selectAll("svg > *").remove()
var val = dropdown.node().options[dropdown.node().selectedIndex].value;

d3.json("test.json", function(error, graph) {
    var filteredLinks = graph.links.filter(d => d.num >= val);
    //Need to map unique source and targets to id in nodes
    var filteredNodes = graph.nodes.filter()//Need a way to map nodes with filteredLinks
      });

    var filteredGraph = {
          nodes: filteredNodes,
          links: filteredLinks
      };
    //do stuff
    })
}
dropdown.on("change", change)
change();

I am seeking guidance on how to complete the JavaScript array manipulation code to filter out links based on num, and also remove the corresponding nodes.

Answer №1

To streamline the process and ensure that nodes are only added once, you can use the node IDs as keys in an object. This way, the nodes array is filtered just once per ID. It's worth noting that this method assumes there are no self-linked nodes, which is usually a rare scenario.

var uniqueNodes = Object.values(links.reduce(function(acc, link){
  if(!acc[link.source]){
    acc[link.source] = allNodes.filter(node => node.id === link.source)[0];
  }
  if(!acc[link.target]){
    acc[link.target] = allNodes.filter(node => node.id === link.target)[0];
  }
  return acc;
},{}))

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to assign a distinct identifier to every hyperlink within a specific class using jquery?

For a project I'm working on, I need to create a list of links and a save button. My goal is to hide the save button if a link has already been saved. To achieve this, I am thinking of assigning a unique ID to each link based on a specific number in t ...

Angular log out function to automatically close pop-up windows

Within my application, there is a page where users can open a popup window. When the user clicks on logout, it should close the popup window. To achieve this, I have used a static variable to store the popup window reference in the Global.ts class. public ...

What is causing my array of objects to constantly accumulate undefined elements?

My quick sort function implementation for the object users_total_likes is behaving unexpectedly. When compiled and run in the terminal or browser, it adds undefined values causing a TypeError: if(users[i][key] >= users[hi][key] && users[j][key] ...

What exactly is the significance of the number 15 passed as the second parameter in the json_encode() function

While exploring Laravel Blade, I observed that the @json($list) directive from the official documentation (https://laravel.com/docs/7.x/blade) gets converted to: <?php echo json_encode($list, 15, 512) ?> I was left wondering about the significance ...

Unspecified binding in knockout.js

As a newcomer to JS app development, I am currently focused on studying existing code and attempting to replicate it while playing around with variable names to test my understanding. I have been working on this JS quiz code built with KO.js... Here is my ...

Arrange fixed-position elements so that they adhere to the boundaries of their adjacent siblings

Is there a way to keep two fixed elements aligned with their sibling element on window resize? <div class="left-img"> IMAGE HERE </div> <!-- fixed positioned --> <div class="container"> Lorem ipsum... </div> <div class=" ...

What is the specific function of jQuery Custom events and how do they operate

I've been on the hunt for reliable sources that delve into the inner workings of custom events in jQuery. Specifically, I want to understand how they replicate event bubbling and more. ...

The connection between `this` and its calling context

Is all information from its call site accessible to a function? I was under the impression that a function would have access to the scope of its call site, but I could be mistaken. Any feedback and explanation would be greatly appreciated. function bar() ...

Preventing the addition of hash tags to the URL by the anything slider

Why does the Anything Slider add hash tags like #&panel1-1 to the end of the URL? I attempted using hashtags:false but it was unsuccessful. Are there alternative methods to prevent it from creating these hashtags? ...

Is it possible in Angular.js to limit the visibility of a service to only one module or to a specific group of modules?

When working with Angular.js, the services declared on a module are typically accessible to all other modules. However, is there a way to restrict the visibility of a service to only one specific module or a selected group of modules? I have some service ...

Customizing the starting number of rows per page in TablePagination from material-ui

As a newcomer to using materials, I am looking to customize the table pagination to show 'n' number of rows, for example 10, and remove the "Rows per page" dropdown. <TablePagination rowsPerPageOptions={[]} component="div" ...

Converting newline characters to valid JSON format in GO

I am facing a challenge converting strings to JSON due to the presence of special characters, such as newlines, which can disrupt the JSON format. While using encoding/json, I noticed that passing a string literal works fine as it automatically adds neces ...

Whenever I repeatedly click the button, the array will store a new value. My goal is for it to collect and store all values obtained from the function

After retrieving data from the listAPI value using an API, the output is displayed as follows: //output - console.log(listAPI) 5) [{…}, {…}, {…}, {…}, {…}] 0: {id: "1", name: "name 1", active: "true"} 1: {id: " ...

Error encountered while attempting to parse text using JSON

Greetings! I have encountered a JSON object that appears like this: {"messages":["operator will assist you"]} However, when I attempt to parse it using $.parseJSON(json), an unexpected character error occurs, specifically SyntaxError: JSON.parse: unexpec ...

Determining where to implement the API display logic - on the server side or

Currently, I am in the process of restructuring an API that deals with user profiles stored in one table and profile images in another. The current setup involves querying the profiles table first and then looping through the images table to gather the ass ...

How to dynamically load bootstrap-multiselect within a loop in a vueJs application

I am attempting to dynamically load bootstrap-multiselect in a loop using VueJs. My desired implementation looks something like this: <div class="col-xs-6 col-sm-4 mb-1" v-for="params in param"> <select class="mult" multiple="multiple"> ...

javascript update HTML content

Hello, I am trying to call a function called changeDivHTML which passes an image. <a href="javascript:void(0)" onclick="changeDivHTML(<img src='.DIR_WS_IMAGES .$addimages_images[$item]['popimage'].'>)"> This function ad ...

Touch Sencha - Continuous Loading in DataView

Hi there! I'm a beginner in sencha touch and currently trying to wrap my head around it. I want to create a simple app that loads a JSON string from a file. Oddly enough, when I test the app on localhost, the dataview shows up perfectly fine. However, ...

Master the art of returning two functions within a single function in Javascript with NodeJS and ExpressJS

Currently, I am facing an issue where I need to combine two objects and return them in one function. The challenge lies in the fact that both objects have almost identical properties, but different values. To tackle this problem, I created two separate fu ...

Converting JSON data to XML format using Laravel

I am looking for a way to convert JSON format to XML using Laravel. Here is the expected output: <MESSAGE> <AUTHKEY>Your auth key</AUTHKEY> <SENDER>SenderID</SENDER> <ROUTE>Template</ROUTE> <CAM ...