How can I efficiently convert data from string to int within a d3 method chain?

d3.js, javascript

Solution

You could map the data before you bind it:

.data(dataset.map(function(d) { return +d; }))

Then unary `+` operator converts a numeric string into a number.

Problem

I'm making an interactive bar chart in d3, and have come across a problem. The bar chart reads data from a form, but it reads the data as a string. When I am using the data to draw bars like this: ``` var bars = svg.selectAll("rect") .data(dataset) .enter() .append("rect") .attr("x", function(d,i) { return i * (w / dataset.length); }) .attr("y", function(d) { return h - (d * 4); }) .attr("width", w / dataset.length - barPadding) .attr("height", function(d) { return d * 4; }) .attr("fill", function(d) { return "rgb(" + (d * redLevel) + ", 0, " + (d * blueLevel) + ")"; }); ``` the data is read as a string. I could use `parseInt(d)` every time I wanted to use `d`, but that would be grossly inefficient. It would be easy to do `var d = parseInt(d)` outside of the method chain, but that wouldn't work with d3. Suggestions?

Original source