The unexpected disappearance of data in a d3 v4 map leaves users puzzled

My current task involves reading data from a csv file and creating a map where the key is the state abbreviation and the value is the frequency of that state in the data.

The code I have successfully creates the map, reads in the data, and when I use console.log(MAP), it outputs correctly.

However, I encounter an issue when I attempt to iterate through the map using .each or .entries() as the map appears to be empty. The method map.size() returns 0.

var statesData = d3.map();
d3.csv("temp-data.csv", function(error, data) {
    if (error) throw error;
    data.forEach(function(row) {
        if (statesData.has(row.state) == false) {
          statesData.set(row.state, 1);
        }
        else {
          statesData.set(row.state, statesData.get(row.state) + 1);
        }
    });
});
console.log(statesData);
console.log(statesData.size());
statesData.each(function(d) {
  console.log("value: " + d);
});

Output:

{}
"$AZ": 1
​
"$CA": 1
​
"$CO": 1
​
"$IA": 1
​
"$KS": 2
​
"$OK": 1
​
"$OR": 1
​
"$PA": 1
​
"$WA": 1
​
<prototype>: Object { constructor: Map(), has: has(), get: get()
, … }
0

https://i.stack.imgur.com/7pWYf.png A picture is also attached for clarification.

temp-data.csv:

id,state,
3,WA
4,OR
5,KS
8,CA
9,CO
11,OK
13,AZ
15,KS
16,IA
17,PA

Although the map contains data, calling .size() results in 0, thus explaining why the .each() method does not output anything.

I am puzzled by this situation and have tried referring to the documentation at but still can't figure out why I can successfully log MAP but cannot iterate through it.

Thank you!

Answer №1

Understood:

Understanding variable scope in d3 javascript

It's important to note that the d3.csv function operates asynchronously, meaning any code relying on its data should be contained within its scope.

This clarifies why the value of statesData is 0 when accessed outside of the d3.csv scope.

The snippet below demonstrates this concept:

var statesData = d3.map();
d3.csv("temp-data.csv", function(error, data) {
    if (error) throw error;
    data.forEach(function(row) {
        if (statesData.has(row.state) == false) {
          statesData.set(row.state, 1);
        }
        else {
          statesData.set(row.state, statesData.get(row.state) + 1);
        }
    });

    console.log(statesData.size())
});

When executed, it correctly displays a size of 9.

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

Preserving the original "this" context while binding a callback for a React child

class Parent extends React.Component { constructor(props) { super(props) this.handleChildOnClick = this.handleChildOnClick.bind(this) } handleChildOnClick() { /* Here, I want to perform an action that involves both Child and Parent. ...

Utilizing jQuery to Sort Table Rows based on an Array of Class Names

I have a table containing values and a filter option where users can select multiple values to filter the table. I want to create a filter with numbers ranging from 1 to 10, and assign class names like filter_1, filter_2, filter_3, etc. to each table row ( ...

Performing a count query with MongoDB Mongoose by grouping data based on multiple fields

I've developed an analytics API using MongoDB. Here is the model for my sessions: const sessionSchema = new Schema( { user: { id: Number, name: String, email: String }, }, { timestamps: true }, ); My goal is to calculate the number of uni ...

Issue with Dropdown Menu functionality while using multiple dropdown options

I am currently experimenting with dropdown menus from W3Schools and have encountered an issue when trying to implement two dropdown options. The code works fine for a single dropdown, but when I try to add a second one using GetElementsByClassName instead ...

Running a Node.js worker on an Amazon ECS-hosted server: A step-by-step guide

Our team is currently running a node server on Amazon ECS that receives up to 100 hits per second. Due to the single-threaded nature of JavaScript, we are hesitant to block the event loop. As a solution, we are looking to implement a worker that can peri ...

"Transferring a JavaScript variable to Twig: A step-by-step guide for this specific scenario

When it comes to loading a CSS file based on the user's selected theme, I encountered an issue while trying to implement this in my Symfony application using Twig templates. The code worked flawlessly on a simple HTML page, but transferring it to a Tw ...

Error occurred while looking for user by ID in the everyauth

I previously had a working example with express 2.*, but now I am transitioning to version 3.*. The issue arises during authentication with Facebook, causing some problems. Everything works fine until everyauth makes the GET request to Facebook and then re ...

Are there any disadvantages to utilizing bindActionCreators within the constructor of a React component when using Redux?

I have come across numerous instances where the bindActionCreators function is used within the mapDispatchToProps function as shown below: ... const mapDispatchToProps = (dispatch, props) => ({ actions: bindActionCreators({ doSomething: som ...

Struggling to Find the Correct Location for Implementing a JSON Dictionary Value in iOS Applications

So, I have been working on a method that creates a URL for an image. Initially, it looked like this: -(NSURL*)urlForImageWithId:(NSNumber*)IdPhoto isThumb:(BOOL)isThumb { NSString* urlString = [NSString stringWithFormat:@"%@/%@upload/%@%@.jpg", ...

What is the best way to extend an inline-block element to cover the entire text line?

Let's talk about the scenario: https://i.stack.imgur.com/we05U.png In the image, there is a container (displayed as a div) with only one child - a span element. The goal is to introduce a second child that occupies the entire red space depicted in t ...

Using JavaScript to insert a value through AJAX

I'm currently working on a website that displays the value of a .TXT file, and here is the progress I've made so far: <script> $(document).ready(function() { $("#responsecontainer").load("info.txt"); var refreshId = setInterval(function( ...

Changing the color of tabs using inline styles in material ui does not seem to work

I am brand new to using material ui and have been attempting to alter the colors of the selected tab. Currently, the color is a dark blue shade and I am aiming to change it to red. I tried applying inline styles, but unfortunately, there was no change. C ...

Should you opt for returning [something] or (nothing) in Javascript with ExpressJS?

Is there a distinct contrast between returning something and returning nothing? Let's take a look at an example: user.save(function(err){ if ( err && err.code !== 11000 ) { console.log(err); console.log(err.code); res.send(&apo ...

Utilizing useState() to manage active link state in Navigation bar component

Learning react and new to the framework. Trying to create a responsive navbar component with material-ui. Works fine on medium devices but struggling with updating active link on smaller devices. Navbar.js ... SideDrawer.js ... C ...

Pressing the reset button will initiate once the loader has finished

Hello everyone, I'm currently working on creating a button that transforms into a loader when submitted and then reverts back to a button after the form is successfully submitted. I suspect the issue lies within my JavaScript. I'm not sure how ...

Transfer of part of a JSON object

My current setup involves an API in PHP that sends JSON data to a Javascript webpage for processing. However, when dealing with large datasets, it can strain both the user's internet connection and computer capabilities. To address this issue, I want ...

The JSON file gets emptied every time I refresh the page repeatedly

I am encountering an issue where my JSON file gets cleared if I restart the page quickly after using the fs module to read/write it. The JSON data is read at the beginning of the page like this: let preferencesJSON; try { preferencesJSON = fs.readFile ...

How can I create an HTML select dropdown menu with a maximum height of 100% and a dynamic size?

The dropdown menu I created using an HTML select tag contains a total of 152 options. However, the large number of options causes some of them to be out of view on most monitors when the size is set to 152. I attempted to limit the number of displayed opti ...

Python, Selenium: Extract Specific Element from List of Results

By leveraging various resources such as reading materials, videos, Stack Overflow, and community support, I successfully extracted data from Tessco.com using a combination of Selenium and Python. Authentication credentials are required for this website. H ...

Instructions on transforming an img into an Image component within next.js

I have successfully implemented all the logic in this component, tailored to the <img> tag. Now, I am aiming to apply the same logic to the Image component. However, when attempting to do so, I encounter an error. TypeError: Failed to construct &apos ...