d3 importing csv file to array [duplicate]

In d3 v5 the API for fetching data has changed quite a bit, which became necessary as the underlying workings have switched from using XMLHttpRequest to the Fetch API. In prior versions of D3 up to v4 your code would have behaved as you expected printing the single resulting array. The new API for d3.csv(), however, look like this:

# d3.csv(input[, init][, row]) <>

Further down the docs provide an explanation for your observation:

If only one of init and row is specified, it is interpreted as the row conversion function if it is a function, and otherwise an init object.

In your code the second argument to d3.csv() is a function and is, thus, interpreted as the row conversion function. Because the row conversion function is executed for every single row in your input file you see each object printed individually instead of the whole array at once.

Since d3.csv() returns a Promise the correct usage would be like this:

d3.csv("data.csv")
  .then(function(data) {
    console.log(data);
  });

Here data refers to the entire array of objects.

Leave a Comment