Does D3 iterate through the entire array every time we define a new callback?

It seems that every time a callback is set, d3 loops through the entire array.

Initially, I thought that functions like attr() or each() were added to a pipeline and executed all at once later on.

I was trying to dynamically process my data within d3's SINGLE loop, and had just discovered each(), which calls a function for each point.

The aim was to convert my points from a javascript object to a single value without having to do so for each callback or in a separate loop.

I tested it out and observed this behavior.

Here is a simple example:

d3.select(ref)
.selectAll("rect")
.data(data)
.enter()
.append("rect")
.each(function(d) { console.log(d); })
.attr("y", function(d) { console.log("attr y"); return 10; })
.attr("fill", function(d) { console.log("fill"); return "red";})

And here is a jsfiddle link: http://jsfiddle.net/7q3p2kah/1/

I expected to see:

red
attr y
fill
green
attr y
fill
...

But what I got was:

red
green
blue
yellow
black
(4)attr y
(4)fill

The purpose of this experiment is to reduce the time taken to display my graphs.

Do I have to use a separate loop to process my data, or is there something I am missing?

Although it may seem like a yes() or no() question, I would appreciate any explanations or alternative solutions.

Answer №1

To improve performance, consider wrapping the attr functions within the each function:

...
.each(function(d) { 
    d3.select(this)
    .call(function(selection){console.log(d);})
    .attr("y", function(d) { console.log("attr y"); return 10; })
    .attr("fill", function(d) { console.log("fill"); return "red";}
})
...

For a more efficient approach, you can check out this example: https://jsfiddle.net/ibowankenobi/wns19k4d/

Consider storing selected nodes in a NodeList or LiveHTMLCollection instead of using d3.select(this). Then you can access them directly like list[i], which may be faster in the long run compared to using d3.select.

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

Discovering the object and its parent within a series of nested arrays

Is there a way to locate an object and its parent object within a nested array of unknown size using either lodash or native JavaScript? The structure of the array could resemble something like this: name: 'Submodule122'</p> I have been ...

Guide to discovering an almost ascending sequence in an Array

I recently encountered a challenging algorithm problem that I need help with: "I have a sequence of integers stored in an array. My task is to determine whether it is possible to obtain a strictly increasing sequence by removing no more than one element f ...

Magnify novice mistakes: Unhandled promise rejection and Ensure every child has a distinct "key" property

Currently, I am working through Amazon's Getting Started with AWS tutorial found here: https://aws.amazon.com/getting-started/hands-on/build-react-app-amplify-graphql/module-four/ After successfully building and hosting the app on git, I noticed that ...

JavaScript/jQuery Tutorial: Accessing the src attribute of images sharing a common class名

How can I extract the src values of images with the same class and display them in an empty div? For instance: <body> <img class="class1" src="http://www.mysite.com/img/image1.jpg" width="168" height="168" alt=""> <img class="class ...

Synchronization issue between CSS style and Javascript is causing discrepancies

I am looking to avoid using jquery for simplicity. I have three websites that each page cycles through. My goal is to scale the webpages by different values. I attempted applying a class to each page and used a switch statement to zoom 2x on Google, 4x o ...

Getting started with html2canvas: A beginner's guide

So here's a seemingly simple question... I'm diving into new territory and stumbled upon http://html2canvas.hertzen.com with a straightforward tutorial. After successfully running the command npm install -g html2canvas, I hit a roadblock. Where e ...

The intersection of JavaScript, node.js, and cybersecurity

I recently set up a user registration form on my website where the data (username, password, email) is currently being sent to the server in plain text using socket.io. I am aware that this method is not secure at all. Can anyone recommend a better solut ...

Issue with onDblClick event in Angular5 and PrimeNG's p-listbox

I encountered an issue while using p-listbox's onDblClick event as it does not return the selected list element. Instead, the event object only contains the value of 'this'. {"originalEvent":{"isTrusted":true}} HTML Blockquote <!-- S ...

What is the process for securing a photo to a canvas?

I have included <input type='file' id="image"> in my HTML code. How can I display the uploaded image on my canvas using p5.js? What is the best way to add an event listener to this action and transfer the uploaded file onto the ca ...

Error: The module '../lib/cli' could not be located

As someone new to the world of JavaScript development, I'm encountering an error while working through the backbone_blueprints book. Here's the specific error message I've come across: > <a href="/cdn-cgi/l/email-protection" class="__ ...

Managing the placement of the expanded autocomplete input in Material-UI

Whenever I use the autocomplete fields on my website, I've observed an interesting behavior. When I select multiple options, the height of the input increases significantly, causing everything below it to shift downward like this. Is there a way to m ...

Cypress - simulate multiple responses for watchPosition stub

I have a small VueJs app where clicking on a button triggers the watchPosition function from the Geolocation API to retrieve the user's position and perform some calculations with it. Now, I want to test this functionality using Cypress testing. To ...

NPM encountered an issue that prevented it from scanning directories due to a permission denial with the error code E

Whenever I type "npm run build:prod" build:prod npm run build -- --configuration production --aot --optimization=false I encounter the following error: > <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="82e4e3ece1fbafece3 ...

Generate a Flask template using data retrieved from an Ajax request

Struggling with a perplexing issue. I'm utilizing Ajax to send data from my Javascript to a Flask server route for processing, intending to then display the processed data in a new template. The transmission of data appears to be smooth from Javascrip ...

Creating components through the command line while managing multiple projects using Angular CLI 6

Currently, I am utilizing the most recent Angular CLI version (v6). Within my codebase resides a collection of applications housed within the projects directory. My objective is to create and organize various modules and components within these projects v ...

What is the process of substituting types in typescript?

Imagine I have the following: type Person = { name: string hobbies: Array<string> } and then this: const people: Array<Person> = [{name: "rich", age: 28}] How can I add an age AND replace hobbies with a different type (Array< ...

Tips for efficiently storing data in the Laravel database using Ajax

I'm attempting to upload a product with multiple images to the database without refreshing the page. Despite not encountering any errors in the console, I am seeing a long block of text that starts like this: <script> Sfdump = window.Sfdump || ...

Call a React component from an external JavaScript file

I am working on a react application that has a bundle.js file created using webpack containing all the necessary code. Recently, I started developing a separate dotnet application and I need to display the main 'App' component from my react appl ...

JavaScript Failing to Validate User Input in Form

I'm a beginner in JavaScript and I'm trying to validate a simple date of birth input, but for some reason, it seems that the JavaScript file is not working. No matter what I input, it always goes through, so I'm trying to figure out what&apo ...

Maintain the modifications in NPM software dependencies

Currently, I am developing a REACT web application and have integrated the react-datasheet library using NPM. To ensure compatibility with IE11, I made modifications to the JavaScript file installed via NPM. While these changes work perfectly on my local m ...