Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

d3 importing csv file to array [duplicate]

Tags:

d3.js

I am trying to import a .csv file using the d3.csv() method. Here is my code:

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

What I thought I would get is an array containing objects, each representing a line of my .csv file (of which there are 50). What I'm actually getting, though, is a series of independent objects. That is, the function has logged 50 objects to my console, not one array containing 50 objects. Am I misunderstanding this method? If so, how can I get such an array?

like image 402
M-N Avatar asked Sep 18 '26 06:09

M-N


1 Answers

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.

like image 195
altocumulus Avatar answered Sep 20 '26 19:09

altocumulus



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!