Javascript d3 reading from csv

Ok, so I'm a bit of a noob with javascript, and I need to read data from csv to create velvet with d3. Barchart is not a problem for me, reading from a csv file. This is my code:

var dataset;
    d3.csv("gender_ratio.csv", function(data) {
    dataset = data;
    return dataset;
});

var add = function(year, total, males, females){
    var year = {
        year: year,
        total: total,
        males: males,
        females: females
    };
    newdata.push(year);
    return newdata;
};

for (var i = 0; i < dataset.length; i += 4){
    add(dataset[i], dataset[i+1], dataset[i+2], dataset[i+3]);
    return newdata;
};

Can someone tell me I'm wrong here? I run this with modzilla firefox, so browser security is not a problem here.

+4
source share
2 answers

A call to load csv data is performed asynchronously. This means that your cycle forstarts before the data is loaded.

If you move the for loop to a callback function to call d3.csv, then the data will be available.

, d3.csv. , , , . console.log , , .

return , , , .

d3.csv("gender_ratio.csv", function(data) {
    dataset = data;
    // process data here
    console.log(data);
});
+4

-, d3 .csv , .csv. csv , :

var dataset = [];
d3.csv("gender_ratio.csv", function(d) {
  return {
    year: d.year,
    total: d.total,
    males: d.males,
    females: d.females,
  };
}, function(error, rows) {
  dataset = rows;
  drawBarChart();  /* <<-- This would be the call to the drawing function. */
});
+4

All Articles