tbl
tbl

Reputation: 903

how to distinct same keys in first line with d3.csv

d3.csv recognizes the first line as a key name automatically. Then, if the first line includes same name keys, we cannot read all data and d3.csv reads only one column.

csv example (Z are same keys)

X,Y,Z,Z
1,4,7,10
2,5,8,11
3,6,9,12

I want to read both of the datum which correspond to the same keys (Z in this example). Maybe we cannot extract "10,11,12" using the d3.csv function.

Could you tell me how to read both of the columns?

Upvotes: 3

Views: 402

Answers (2)

mdml
mdml

Reputation: 22882

Building off of @musically_ut's answer, you could do something like the following:

d3.text("txt.csv", function(err, txt){
    var rows = d3.csv.parseRows(txt),
        header = rows.shift(),
        data = rows.map(function(r){
            var obj = {};
            r.forEach(function(c, i){
                if (!(header[i] in obj))
                    obj[header[i]] = c;
                else
                    obj[header[i]] +=  " " + c;
            });
            return obj;
        });
});

Here, like with d3.csv, you are creating an object for each row of the CSV file with keys corresponding to the column names. Unlike with d3.csv, if two columns have the same name, this method just appends the data in both columns together (see example below).

If you output the resulting data using this method, you get the following:

>> console.log(JSON.stringify(data));
[{"X":"1","Y":"4","Z":"7 10"},
 {"X":"2","Y":"5","Z":"8 11"},
 {"X":"3","Y":"6","Z":"9 12"}
] 

Upvotes: 0

musically_ut
musically_ut

Reputation: 34288

You are correct that d3.csv will not be able to extract the complete data.

However, if you have a custom data format, then use d3.text to load the data as a text file. Then you can parse it in your custom format using d3.csv.parseRows.

This will give you an array of arrays which you can then d3.transpose to find your columns.

Upvotes: 1

Related Questions