csv to array in d3.js

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:

first();
d3.csv("path/to/file.csv", function(rows) {
  third();
});
second();

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 third is, above):

d3.csv("path/to/file.csv", function(rows) {
  doSomethingWithRows(rows);
});

function doSomethingWithRows(rows) {
  // do something with rows
}

Or, you might save it as a global variable on the window that you can then refer to later:

var rows;

d3.csv("path/to/file.csv", function(loadedRows) {
  rows = loadedRows;
  doSomethingWithRows();
});

function doSomethingWithRows() {
  // do something with rows
}

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:

d3.csv("path/to/file.csv", function(rows) {
  window.rows = rows;
  doSomethingWithRows();
});

function doSomethingWithRows() {
  // do something with rows
}

I think your problem is timing because it is an async call. So, load the data as you have but call the function within the d3 code (where Mike has 'doSomethingWithRows()'). Don't follow your d3 code with any more processing (where Mike has 'second()'), move that code into the 'doSomethingWithRows()' function. It will have the data available and away you go...

Tags:

Csv

D3.Js