Copy data from csv to array in D3

I know this question has been asked before, but their solutions cannot work for me for some reason.

I am trying to populate two arrays with data from a CSV file, where:

name,value
alpha,34
beta,12
delta,49
gamma,89

Now i try to execute

var field1=[];
var field2=[];

d3.csv("data.csv",function(csv){
            csv.map(function(d){
                field1.push(d.name);
                field2.push(+d.value);
            })
        });

console.log("field1",field1);
console.log("field2",field2);

When I view the console in my browser, I see:

Field1 Array [] field2 Array []

Where:

field1:
Array[0]
  0:"alpha"
  1:"beta"
  2:"delta"
  3:"gamma"

field2:
Array[0]
  0:34
  1:12
  2:49
  3:89

However, when I try to access field1 [0], I get the value as undefined

field1 undefined

I assume that the array field1 has an array of arrays of the "name" column, but I cannot access the first element, although the field is [0] [0]. I get:

TypeError: field1[0] is undefined 

JavaScript, , , , - . , csv , csv , script.

, , :

, , -.. , !

+4
1

,

d3.csv("data.csv",function(csv){

- ajax, - ( ajax, ):

var field1=[];
var field2=[];

d3.csv("data.csv",function(csv){
            //executed after successful loading of data
            csv.map(function(d){

                field1.push(d.name);
                field2.push(+d.value);
            })
        });
//called before the loading of AJAX call got completed
console.log("field1",field1);
console.log("field2",field2);

:

var field1=[];
var field2=[];

d3.csv("data.csv",function(csv){
            csv.map(function(d){
                field1.push(d.name);
                field2.push(+d.value);
            })
            //called after the AJAX is success
            console.log("field1",field1);
            console.log("field2",field2);
            console.log("field1",field1[0]);
        });

, !

+2

Source: https://habr.com/ru/post/1626658/


All Articles