Using JS and d3.js to eliminate or combine duplicate connections in a d3.js node diagram

Hey there!

Hello, I am new to working with js/d3.js and tackling a small project. Here are some of my previous inquiries:

  • D3.js: Dynamically create source and target based on identical JSON values
  • JS / d3.js: Steps for highlighting adjacent links

My current project involves dynamically generating source and target pairs based on user inputs. However, I have encountered an issue where there are duplicate links among nodes. Upon investigation, I noticed that the duplication may be stemming from repeated Source/Target elements in the array being created. Below is a snippet showing what happened within the 'links' array:

//Source and target serve as unique identifiers for each datastruct
source: S001A, target: S002A
source: S001A, target: S003A
source: S001A, target: S004A       
source: S002A, target: S001A //Duplicate
source: S002A, target: S005A
source: S003A, target: S001A //Duplicate
source: S003A, target: S006A
source: S004A, target: S001A //Duplicate
                  ...

The cause of this issue lies in my raw data having a nested array for "Friends". Here's an example entry in the dataset:

{
   "NRIC": "S001A",
   "name": "Benjamin",
   "blk": 123,
   "estate": "Woodlands",
   "street": "Woodlands Street 12",
   "unitNo": "01-23",
   "postal": 123123,
   "school": "Nanyang Technological University",
   "Friends": //Nested array..
   [
      "S002A",
      "S003A",
      "S004A",
   ]
}

Below is the for-loop I've been utilizing to generate the source-target arrays for the nested data:

graphData.forEach(function(gdata,index)
{
    for (i = 0; i < gdata.Friends.length; i++)
    {
        links.push({
            source: gdata.NRIC,
            target: gdata.Friends[i]
        });     
    }
});

This loop inevitably leads to duplicates since friends are mutually included in each other's lists. (For instance, S001A is friends with S002A, S003A, and S004A - and vice versa).

I initially considered only using source/target pairs where source === this.id, but I fear this might result in omitting essential pairs and compromising data integrity.

Is there a way I can iterate through and eliminate these redundant pairings from the array? Whether by adjusting the existing for-loop or implementing post-processing on the data.

Thank you immensely for your guidance!

Answer №1

Shout out to @Gerardo Furtado for the assistance!

I made some adjustments to the solution in order to sort alphanumeric values. Here is the modified version that I used:

graphData.forEach(function(gdata,index)
{
    for (i = 0; i < gdata.Friends.length; i++)
    {
        links.push({
            source: gdata.NRIC,
            target: gdata.Friends[i]
        });     
    }
});

links.forEach(function(d) {
    var sourceTemp = d.source, targetTemp = d.target;
    if (d.source > d.target)
    {
        d.source = targetTemp;
        d.target = sourceTemp;
    }
});

//links.sort(); doesn't work as item to be sorted may be alphanmueric :(
var linkslength = links.length;

links.forEach(function(d,i)
{
    var curSrc = d.source, curTgt = d.target;
    for(var j = i+1; j < linkslength; j++)
    {
        if (links[j].source === curSrc && links[j].target === curTgt)
        {
            links.splice(j,1);
            linkslength -= 1;
        }
    }
}); 

I understand that this code can be optimized further. Any suggestions on reducing the number of loops? Also, I am concerned about the updates to links.length after each splice operation. I manually adjusted it in the code.

Huge thanks to Gerardo Furtado and the Stack Overflow community! Cheers :)

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

A dynamic JQuery carousel displaying a variety of albums

I'm searching for a jQuery gallery or slider that can accommodate multiple albums without needing to load a new page each time. I don't need anything too fancy, just the ability to have links above the content. I have knowledge in html, css, and ...

Methods for displaying data on the client side using express, MongoDB, and jade

I'm currently working on displaying data retrieved from my database using node.js, Express, and MongoDB. I successfully see the data in the console, but now I need to output it on the front-end using Jade. Here is the data I have retrieved: { date: ...

I encountered an issue while constructing a React application. An error message popped up indicating: "Warning: Can't execute a React state update on a component that is not mounted"

Having difficulty pinpointing the source of the error message displayed below. Should I focus my investigation on the specific lines mentioned in the console, such as Toolbar.js:15? Is the console indicating that the error lies there? Additionally, what i ...

Error: Unable to locate module: Unable to resolve 'next/web-vitals'

I keep encountering the following error message: Module not found: Can't resolve 'next/web-vitals' I am interested in utilizing the **useReportWebVitals** feature from next/web-vitals. For more information, please visit: Optimizing: Analyt ...

How to stop empty numbers in angular.js

My goal is to ensure that an input with a required attribute always has some value, and if left empty, defaults to zero. <input ng-model='someModel' required> I have created the following directive: App.directive('input', fun ...

Error: The 'length' property cannot be searched for using the 'in' operator

Hmm, I keep getting an error that says "Uncaught TypeError: Cannot use 'in' operator to search for 'length' in" Every time I attempt a $.each on this JSON object: {"type":"Anuncio","textos":["Probando ...

I am in need of a datepicker for my project that will display the END date as the current date and set the START date as 7 days before the END date

$(document).ready(function () { $("#end").datepicker({ dateFormat: "dd-M-yy", minDate: 0, onSelect: function () { var start = $('#start'); var startDate = $(this).datepicker('getDate') ...

Press on the div to reveal its content at the clicked position

Hello, I have a query that I need help with. I currently have a basic table with buttons in columns that act as filters. When you click on one of these buttons, it opens up a form. https://i.sstatic.net/nuEpq.png What I am trying to achieve is to make t ...

Is it possible for me to customize the default angular filter in order to prioritize displaying strings that begin with the search term?

In my current project, we are dealing with a massive list of strings (17,000+ at times) and have implemented an input box for filtering the list. Initially, I used Angular's default filter, but then a request came in to sort the list so that strings s ...

Debugging the Force-Directed D3 Graph

I stumbled upon a fantastic article that provided a detailed guide on creating a beautiful D3 force layout graph. However, I'm facing some difficulties with the JSON source: The "links" attribute in the author's JSON doesn't seem clear to m ...

I am having trouble retrieving the content-length from the response headers within the app.use() middleware function

Can anyone help with retrieving the content-length from response headers within the app.use() middleware function? const app = express(); app.use((req, res, next) => { // Need to find a way to access content-length of res console.log("co ...

Encountering a React clash while integrating Material UI

Upon trying to utilize the AppBar feature in Material UI version 0.16.6, I encountered the following error: Uncaught Error: addComponentAsRefTo(...): Only a ReactOwner can have refs. You might be adding a ref to a component that was not created within a c ...

Automatically navigate to a different page using JavaScript after 5 seconds without interrupting the execution of other code

Is there a way to redirect to a specific URL after 5 seconds without halting the execution of other code on the page? I want all the other code to run first before triggering the redirection. Wrapping the entire page in a setTimeout block is not an option. ...

Code snippet for adding a div element with an embedded image using JavaScript

I am attempting to create a function that generates three div elements, each containing an image, and then appends them to the body using a for loop. As a beginner in JavaScript, I am struggling with this task. Can anyone please provide guidance on what ...

Javascript Encapsulation example

Could someone help me with this function query: var MyObject3 = function (a, b) { var obj = { myA : a, myB : b } ; obj.foo = function () { return obj.myA + obj.myB ; } ; obj.bar = function (c) { return obj.myA + c ; } ; return obj ; } ; I und ...

Koa.js route() isn't a defined function

Recently, I created a basic koa app that should return rss xml based on a tag using a parameter. However, for some reason the middleware is unable to read the router from the router file and I cannot figure out why it's not working as expected. The ap ...

Transforming a sequence of numerical values into an array in Java, with each number occupying a distinct position

If I have a string consisting of the numbers 123456789, how can I separate each digit and store them in different slots of an array without using the split() method in Java? ...

Algorithm for encryption and decryption using symmetric keys

Can anyone recommend a reliable symmetric-key encryption algorithm that works seamlessly with both JavaScript and Java programming languages? I attempted to implement one myself, but encountered some complications related to encoding. ...

What is the reason behind this Uncaught TypeError that is happening?

After converting my questionnaire to a PHP file and adding a validation script, I encountered an error: Uncaught TypeError: Cannot set property 'onClick' of null The error is pointing me to line 163 in my JavaScript file, where the function f ...

Having trouble converting NSData object to NSDictionary

Could there be an issue with the JSON output that is causing strange encoding when trying to extract information from a JSON file found on a blog? JSON: [{ "title": "A visit to McSorley\u0027s Old Ale House", "subtitle": "", "summary": "&bs ...