I’m using D3 with JSON data with a function similar to this:
d3.json("http://api.json", function(jsondata) {
var data = jsondata.map(function(d) { return d.number; });
This causes data to equal ["2", "5", "8", "12"]
Then if I use:
var x = d3.scale.linear()
.domain([0, d3.max(data)])
The max returned is 8 instead of 12. I realize this is because 8 is greater than 1 in 12, but I’m not sure how to fix this. Thanks!
Per the API reference, d3.max returns the maximum value using natural order. Since you are computing the maximum of an array of strings, lexicographic (alphabetical) order is used. Compare:
If you want to compute the numeric maximum of an array, you should probably convert those strings to numbers first. A convenient way of doing that is the unary
+operator:If you prefer, you can also use parseFloat, parseInt, Number or a variety of other methods to coerce strings to numbers. Technically, you could do this as part of the d3.max call (
d3.max(data, Number)), but it’s generally faster and safer to do the coercion explicitly.Of course, since you’re already using JSON and JSON is a typed serialization format, it might also make more sense to store numbers in JSON rather than strings; then you won’t need any type coercion.