How can Array.map() be combined with D3 selection?

Is there a way to calculate the maximum length of text elements in an SVG selection similar to using Array.map()? Currently, I am retrieving the maximum length of a selection of SVG <text/> elements by utilizing .selectAll(...)[0].map(...), but it feels like a workaround. Is there a more efficient approach?

      var chi = svg.selectAll('.chi');

      var xChi = d3.max(chi[0].map(function (itm) { return itm.getComputedTextLength(); }));

I am familiar with using selection.each() to iterate a function over a selection, however, I am unsure how to incorporate d3.max() into this process. My attempt at using

d3.max(chi.each(function (itm) { return itm.getComputedTextLength(); }))
was unsuccessful since d3.each() does not generate an array of the returned values.

Answer №1

let textLengths;

d3.selectAll(".element")
.each(function(d, i) {textLengths[i] = d3.select(this).node().getComputedTextLength() })

const maxTextLength = d3.max(textLengths);

Answer №2

Yeah, that bracket really strains my eyes too.

d3.max(svg.selectAll('.chi').pop(), function(el) {
  return el.getComputedTextLength()
})

This question dates back to 2012. I can't speak for the older versions of d3, but in the current version, d3.max now allows for an accessor function to determine the value to maximize.

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 prematurely exit an outer function when there are multiple inner non-blocking function calls?

For the purpose of learning, I am working on creating a basic version of async.parallel. The description from the documentation is as follows: parallel(tasks, [callback]) Run the tasks array of functions in parallel, without waiting until the previou ...

Using Angular function to retrieve Firebase snapshot

Trying to access a user's profile image stored in Firebase at /user/[uid]/info/photoURL This is being done using Angular functions. Here is the code snippet: HTML: <img ng-src="{{getImg(user.uid)}}" alt=""> Javascript: $scope.getImg = func ...

Adjust the div's height to 0

I need to dynamically set the height of a div element with a height of 34px to 0px. However, this div does not have a specific class or ID, so I can't use traditional DOM manipulation methods like .getElementById(), .getElementByClassName, or .getElem ...

Converting data to JSON geometry format for implementation in Three.js

Currently, I am in the process of creating an exporter using Maxscript to convert data into JSON format for use in Three.js. Information on this topic is scarce, but I did come across a helpful resource: https://github.com/mrdoob/three.js/wiki/JSON-Geometr ...

Tips for clearing text inputs in ReactJS

In my current Reactjs project using nextjs, I am facing an issue with clearing input fields after a click event. Below is the code snippet that I have been working on: <form onSubmit={handleSubmit}> <input type="text" ...

Tips on preventing form submission when clicking on another button within the same form

I created a shopping cart page with functionality to adjust the quantity using JavaScript. I have shared some of the HTML code below, <form action="payment.php" method="post"> <div class="qty__amount"> ...

What's preventing me from using the left click function on my published blog post?

This is my first time creating a blogger template and everything seems to be working correctly. However, I have encountered one problem. For some reason, I am unable to left click on my blog post. I have not installed any right/left click disabler and I&a ...

What is the best way for me to determine the average number of likes on a post?

I have a Post model with various fields such as author, content, views, likedBy, tags, and comments. model Post { createdAt DateTime @default(now()) updatedAt DateTime @updatedAt id String @id @default(cuid()) author U ...

It appears that the flex-grow property is not functioning as expected

I am working with a parent div and two children divs underneath it. I noticed that when I set the flex-grow property of the first child to zero, its width remains constant. However, if I add text to the second child, the width of the first child decreases. ...

Ways to determine if an element is at the top of a page

I need help with a test case that involves checking if the title scrolls up to the top of the page when a button is clicked. The challenge is that there is a default header on the page, so the title should scroll below that. How can we verify this scenar ...

Accessing a child field from Firebase in a React Native application

My firebase data is structured like this: "Locations" : { "location01" : { "image" : "https://www.senecacollege.ca/content/dam/projects/seneca/homepage-assets/homepage_intl.jpg", "instructorNa ...

what is the best way to center list items in material ui?

I have been attempting to align the list items (checkbox, text, and buttons) within a Material UI list in the center, but all my attempts have been unsuccessful. Is there anyone who knows how to resolve this issue? Your help would be greatly appreciated! h ...

Issue with Restangular/angularjs object not refreshing after remove() operation

I am currently using Restangular within my AngularJS application. I have an index view that displays all messages, and I can edit and add messages to the list without any issues. However, when I attempt to use the remove() function on an element, the index ...

Using Vue.js watchers can sometimes cause an endless loop

I'm working on a unique aspect ratio calculator. How can I ensure my code doesn't get stuck in an endless loop when dealing with 4 variables that are dependent on each other? To address this, I implemented 4 watchers, each monitoring a specific ...

Tips on using JQuery to extract form field information from a drop-down menu, display it in a div, and then compare it with the subsequently

In my HTML file, I am using two dropdown lists and JQuery for validation. First, I need to save the selected items from both dropdown lists in a variable and then compare them with the next selection. If the data from both dropdown lists match, an alert m ...

The newly added radio button does not function as a separate group as expected

I currently have a set of radio buttons: <input type="radio" class='form-control' name="progress_type[]" value="Journal Papers"><span class='radio-label'>Journal Paper</span> <input type="radio" class='form-co ...

Manipulating lines and positions with jQuery

I am looking to implement a feature that allows users to choose a specific region on an image using jQuery. The functionality should be similar to the tagging feature on Facebook, but with the added bonus of being able to rotate and scale the selected area ...

Success callbacks parsed from AJAX requests

When dealing with a Backbone object and making an AJAX call to save it, I often wonder about the different ways the success callback can be handled. Sometimes, I see a generic success: function (data) { console.log(data); Other times, it's more spec ...

What purpose does the next() function serve in Express.js?

Using this script to kickstart my next js app. I can't share the entire script, but I do need some assistance with the following: What is the purpose of compression? What is the importance of using helmet? What does next({dev}) do? const express = re ...

Express.js: Initial Request Fails to Retrieve Set Cookie

In my Express.js application, I am facing an issue where setting a cookie in one middleware function results in it being undefined when attempting to access it in the following middleware function on the initial request. Strangely, on subsequent requests, ...