score:0

Accepted answer

The 'columns' property

In D3 v4.x there is a new feature that comes in handy: when you load a data file using d3.csv (as well as d3.tsv and d3.dsv) an array property called columns is created.

According to the API:

The returned array also exposes a columns property containing the column names in input order (in contrast to Object.keys, whose iteration order is arbitrary).

Let's see how we can use it.

First, have a look at the following demo (I'm using a <pre> element here because I cannot use a real csv file in the Stack snippet). As you can see in the console (with the first object of the data array), all those numbers are actually strings:

var data = d3.csvParse(d3.select("#csv").text());

console.log(data[0])
pre{
  display: none;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<pre id="csv">word,stamp,year1data,year2data,year3data,year4data
foo,a,2,4,6,3
bar,b,8,4,6,2
baz,c,3,7,8,5</pre>

However, we can use data.columns, which in our case is...

["word", "stamp", "year1data", "year2data", "year3data", "year4data"]

... to iterate over all columns in the data array.

In the following snippet, we use the columns array to coerce the value of all columns that are not "word" or "stamp", since these columns should have strings. This is the function:

data.forEach(function(d) {
    data.columns.forEach(function(e) {
        if (e != "word" && e != "stamp") {
            console.log(e)
            d[e] = +d[e]
        }
    })
});

And here is the demo:

var data = d3.csvParse(d3.select("#csv").text());

data.forEach(function(d){
	data.columns.forEach(function(e){
  	if(e != "word" && e != "stamp"){
    	d[e] = +d[e]
    }
  })
});

console.log(data[0])
pre{
  display: none;
}
<script src="https://d3js.org/d3.v4.min.js"></script>
<pre id="csv">word,stamp,year1data,year2data,year3data,year4data
foo,a,2,4,6,3
bar,b,8,4,6,2
baz,c,3,7,8,5</pre>

In conclusion, you don't need to manually specify all the columns, specially in your case, where you have 60 or more columns. Just use data.columns.


Related Query

More Query from same tag