Kai Daniel
Kai Daniel

Reputation: 3

d3.csv doesnt load numeric matrix

I want to load an external .csv file using d3.csv.

This is data.csv (created in vim):

x,y
2,2
99,18

This is the d3 code:

d3.csv("data.csv", function(dataset){
console.log(d3.max(dataset, function(d){return d["y"];})); 
});

Even though I expected '18' the output in the console I get is '2'. If I change the '18' to another number, e.g. '35' the output is correct again. What am I doing wrong?

Upvotes: 0

Views: 429

Answers (1)

meetamit
meetamit

Reputation: 25157

These numbers are getting loaded as Strings, and that's causing unexpected behavior of d3.max. You need to cast the values into Numbers.

You can turn them into numbers via Number(d.y) or (parseInt, parseFloat). In d3 you often see it shortened as y: +d.y.

With d3.csv you can specify a function where you can do this conversion as it parses. See documentation.

Upvotes: 1

Related Questions