How Do I Read A Csv File Into An Array Using D3js V5
Solution 1:
When you run your code you should see that you are indeed loading the data. When I use your example data in a dsv/csv file and run your function I get the following logged to console:
So it appears as both your load of the dsv file is successful, and your row function is successful, based on the console log in the then
method.
Let's take a closer look at the .then
method, this runs after the file has loaded and the row function been applied - or, once the promise has been fulfilled. So the key part here is the then
method doesn't execute the provided function until after the promise is fulfilled. While we are waiting for the the promise to be fulfilled, code continues to be executed, in your case the return statement executes - before the data is fully loaded and therefore before the then method executes. This means you aren't returning any data, and this is your problem.
The simplest and probably most common d3 patterns to fetch the data with your row function is to either place code that requires the loaded data in the .then method's fulfillment function:
functiongetCSVdata() {
d3.dsv(";","https://raw.githubusercontent.com/Andrew-Reid/SO/master/dsv.csv", function(d) {
return {
State : d.Country,
freq: {
low : d.Car,
med : d.Van,
high : d.Truck
}
};
}).then(function(data) {
console.log("file has " + data.length + " rows");
logger(data);
});
}
getCSVdata();
functionlogger(data) {
console.log(data);
}
.as-console-wrapper { max-height: 100%!important; top: 0; }
<scriptsrc="https://d3js.org/d3.v5.min.js"></script>
Or you could take a slightly different form:
functiongetCSVdata() {
d3.dsv(";","https://raw.githubusercontent.com/Andrew-Reid/SO/master/dsv.csv", function(d) {
return {
State : d.Country,
freq: {
low : d.Car,
med : d.Van,
high : d.Truck
}
};
}).then(fulfilled);
}
getCSVdata();
functionfulfilled(data) {
// do stuff here:console.log(data);
}
.as-console-wrapper { max-height: 100%!important; top: 0; }
<scriptsrc="https://d3js.org/d3.v5.min.js"></script>
Post a Comment for "How Do I Read A Csv File Into An Array Using D3js V5"