0

I need to read csv file with d3.js. My data file is

x,y
480,200
580,400
680,100
780,300
180,300
280,100
380,400

and my code is

var ball_1 = []
d3.csv("data.csv", function(data) {
    ball_1 = data.map(function(d) { return [ +d["x"], +d["y"] ]; });
    });
console.log(ball_1)

and the console log says

Array [ ]

but if I just write the data array explicitly in code,

var ball_1 = [
    [480, 200],
    [580, 400],
    [680, 100],
    [780, 300],
    [180, 300],
    [280, 100],
    [380, 400]
    ];
console.log(ball_1)

Then console log says

Array [ Array[2], Array[2], Array[2], Array[2], Array[2], Array[2], Array[2] ]

So the first code for reading csv file does not work. What's wrong?

MMK
  • 3,673
  • 1
  • 22
  • 30
user42298
  • 1,831
  • 3
  • 19
  • 30

1 Answers1

2

d3's methods json(), csv() and tsv() are asynchronous. that means that you should write

var ball = [];

d3.csv('yourfile.csv', function(err, data){
    ball = data.map(function(d) { return [ +d["x"], +d["y"] ]; });

    console.log(ball); //here the code is executed when the csv is retrieved
});

console.log(ball); //here the code is executed after d3.csv() is launched

depending on how fast the server is, you should see

Array[]
Array[7]