I am using this to parse a csv file and create an array data as specified in d3 docs:
d3.csv("afile.csv", function(data) {
data.forEach(function(d) {
d.date = formatDate.parse(d.date);
d.price = +d.price;
});
However, if after this method I try to call data[0] it says it is undefined. Is this because data is a reference and once d3.csv() is out of scope is destroyed? If this is the case how can I overcome this. I need to reference data out of d3.csv()
d3.csv is an asynchronous method. This means that code inside the callback function is run when the data is loaded, but code after and outside the callback function will be run immediately after the request is made, when the data is not yet available. In other words:
If you want to use the data that is loaded by d3.csv, you either need to put that code inside the callback function (where
thirdis, above):Or, you might save it as a global variable on the window that you can then refer to later:
If you want, you can also assign the loaded data explicitly to the window object, rather than declaring a variable and then managing two different names: