Attempting to implement a dynamic radius feature in d3.js but encountering an issue with the error message: "TypeError: size is not a function

I came across a helpful post on StackOverflow about dynamically setting the size of a node in my graph based on the number of links it has. The link is provided here: D3 Node radius depends on number of links : weight property.

Following the guidance from the StackOverflow answer, I implemented the dynamic weight calculation for each node in my graph like this:

node.append("circle")
.attr("r", function(d) {
   d.weight = links.filter(function(l) {
     return l.source.index == d.index || l.target.index == d.index;
   }).size();
   var minRadius = 10;
   return minRadius + (d.weight * 2);
 });

However, during the implementation, I encountered an error message:

TypeError: links.filter(...).size is not a function

I'm puzzled by this error and unsure about what mistake I might have made. Any suggestions?

Here is the full script that I've been working with:

d3.dsv(",", "board_games.csv", function(d) {
  return {
    source: d.source,
    target: d.target,
    value: +d.value
  }
}).then(function(data) {

  var links = data;

  var nodes = {};

  // code to compute distinct nodes from the links...

}).catch(function(error) {
  console.log(error);
});

Answer №1

After some trial and error, I finally cracked the code. The example stack overflow post used size() which left me puzzled, but switching to length did the trick for me.

node.append("circle")
      .attr("r", function(d) {
         d.weight = links.filter(function(l) {
           return l.source.index == d.index || l.target.index == d.index
         }).length;
         console.log("d weight", d.weight)
         var minRadius = 10;
         return minRadius + (d.weight * 2);
       });

Answer №2

When utilizing your attr("r") function, make sure to avoid setting d.weight = 5; after the dynamic computation has occurred. This action will result in all nodes having a weight of 5. For proper functionality, simply remove that line and let the computed weight take effect:

  node.append("circle")
      .attr("r", function(d) {
         d.weight = links.filter(function(l) {
           return l.source.index == d.index || l.target.index == d.index
         }).size();
         var minRadius = 10;
         return minRadius + (d.weight * 2);
       });

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

Error: The property 'setCrossOrigin' is not defined and cannot be read

When I try to run both .obj and .mtl files together, I encounter an error, whereas running just the .obj loader works fine. The specific error message that appears is: MTLLoader error Below is the code snippet I am using to load the .obj and .mtl files: ...

Why is it that $.when() doesn't wait for the function to finish executing?

I am facing an issue where the timer timeout is being perceived as the completion of the "wait" function, instead of waiting for the execution of the "removeDocx" function. How can I fix this problem and update the page only after the "removeDocx" functi ...

Steps for populating a dropdown list with a JSON response

I'm facing a challenge in inserting server data into a dropdown list because each object name begins with a random ID. Here's what I'm attempting to achieve here: $("#CampaignOpenActionSubscriber_campaign_id").change(function() { var el ...

Error when saving data in database (MongoDB) due to a bug

When setting up a database schema, sometimes an error occurs in the console indicating that something was not written correctly. How can this be resolved? Here is the code: let mongoose = require(`mongoose`); let Schema = mongoose.Schema; let newOrder = ...

Why is it displaying undefined even though there is data stored in Firebase?

I am experiencing an issue where the datatable row is displaying "undefined" instead of the data from my Firebase database. Even when I tried inserting random data into the HTML file for the datatable, it still shows undefined. Here is a link to My Datata ...

`Is there a right way to utilize the Vuex store effectively?`

I'm currently grappling with a logical challenge regarding data storage in Vuex. <ul> <li v-for="category in sub_categories" @click="setProductCategory(category);"> <span v-bind:class="{active: category == product.category} ...

Clicking to fade in and out with jQuery on data attributes

I have structured my HTML code as follows: <div class="col-sm-8"> <img id="click-1" class="glasses one active" src="<?php bloginfo('template_directory'); ?>/assets/images/Statesman-Three.png"/> ...

Utilize JavaScript to enable printing capabilities for multiple printers

Does anyone know how I can print two different types of documents on two separate printers without the print window showing up? I typically use "Always print silent" on Firefox to avoid the print window, but this won't work for printing on two differe ...

What is the best way to set a CSS background using vue-cli 3?

What is the process for setting a CSS background in vue-cli 3? I have set my vue.config.js like this. Is publicPath properly configured? JavaScript const path = require("path"); module.exports = { devServer: { port: 8081, overlay: { warni ...

Generate a React component for every item within a JSON data structure

I am seeking advice on how to efficiently render React components for each element in a JSON object, specifically when using Firebase database. I am attempting to create an array of book data and store it in an array called bookKeysArray which I plan to us ...

Improper Placement of TransformControls in three.js

Using the following code snippet, I am able to generate a box: let v = [ new THREE.Vector3(-100,30,10), new THREE.Vector3(-100,30,-10), new THREE.Vector3(-100,-10,10), new THREE.Vector3(-100,-10,-10), ...

Unable to modify the value of an object variable generated from a query in JavaScript, ExpressJS, and MongoDB

Here is the code snippet I've been working on: let addSubmissions = await Submission.find({"type": "add-information"}, (err) => { if(err) { console.log(err) req.flash('error', 'No "add submissions" were found&apo ...

Using SignalR 2.0 to connect to a hub without relying on a proxy

By using the HTML/JS code below, I have been able to successfully connect to my SignalR 2.0 hub when both the HTML/JS and hub are on the same server. <!DOCTYPE html> <html> <head> <title>Test SignalR 2.0</title> <style typ ...

Ways to extract a parameter from a React component

Currently, I am working with React and using an API call (ReviewerService.getReviewers()) that returns an array of values: 0: {id: 1, firstName: 'John', lastName: 'Doe', email: '<a href="/cdn-cgi/l/email-protection" class="__cf_ ...

Retrieve the personalized data-* attributes from a specific item within an array

I'm struggling to find the correct syntax for accessing custom data-* attributes for list elements within an unordered list that has been sorted and converted into an array using the following code: $("#gridlist").sortable("toArray"); The list eleme ...

Implementing file uploads using AJAX in CodeIgniter will continue to run, even if the value is null or undefined

I need to trigger another ajax request if the file has not been input yet. However, it is currently still carrying out the form action. Below is my view code: <form method="POST" id="quiz_file" action="<?php echo site_url('home/upload_quiz/&ap ...

Is it possible to retrieve 2 arguments within a function in a non-sequential manner?

Let's say there is a function with arguments A, B, C, D, and E. Function(A, B, C, D, E) However, not all arguments are needed all the time. For instance, only A and C are needed in some cases. Currently, I would have to call the function like this: Fu ...

Looking to display all items once the page has finished loading

I am experiencing a minor issue. Every time I access my store page where all products are listed, I have to click on the size filter to load the products. This is not ideal as I want all products to be displayed automatically when the page loads. What modi ...

Looking to construct dynamic checkboxes in Angular by parsing a JSON object retrieved through AJAX

I have a JSON document structured like the example below, and I am looking to generate checkboxes dynamically using Angular. let data = { "Name":[ { "tagId":4489,"name":"Name","label":"Employee Name" } ], "Service":[ { "tagId": ...

The browser encountered an issue trying to load a resource from a directory with multiple nested levels

I've stumbled upon an unusual issue. Here is a snapshot from the inspector tools. The browser is unable to load certain resources even though they do exist. When I try to access the URL in another tab, the resource loads successfully. URLs in the i ...