Curtman
Curtman

Reputation: 25

D3 scales - why does multiplying by 1 make a difference?

I am working on a retirement calculator/bar chart with d3.js. I built the bar chart to display a static array, and then connected the chart to my retirement equation.

When I connected my chart to my calculator, my yScale was wrong even though the input arrays were the same. I fixed it by changing this:

const yScale = d3.scaleLinear().domain([0, d3.max(fvArr,(d)=>d[1])]).range([height-padding,0]);

to this:

const yScale = d3.scaleLinear().domain([0, d3.max(fvArr,(d)=>d[1]*1)]).range([height-padding,0]);

Why did this work? Codepen is here.

Upvotes: 1

Views: 111

Answers (1)

Gerardo Furtado
Gerardo Furtado

Reputation: 102194

The problem here is that your data contains strings, not numbers.

If you look at the fvArr array you'll see this:

[[0, "30000"], [1, "32800"], [2, "35768"] etc...]

So, what the multiplication is doing here is just coercing the result to a number. Check this:

console.log(typeof("5" * 1))

That is the same of using the unary plus, which is way more common:

console.log(typeof(+"5"))

Upvotes: 2

Related Questions