D3 Bar chart project

Why it is necessary to do the following?

  1. var xMax = new Date(d3.max(yearsDate))
    and not
  2. var xMax = d3.max(yearsDate) // since yearsDate elements are dates

Note: I tried option 2) and the last bar is detached from the other bars but when doing option 1) it worked - all bars are together.
So, why it is necessary to use new Date with d.max() even though the value returned by d.max() is a date - isn’t it?
Thank you.

Your code so far

Your browser information:

User Agent is: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/96.0.4664.110 Safari/537.36 Edg/96.0.1054.62

Challenge: Visualize Data with a Bar Chart

Link to the challenge:

d3.max() will return the largest of whatever group of things you give it. So if yearsDate is an array of Date objects, it should return a Date. If yearsDate is another type, then it will return that type, which may be convertible to a Date with new Date(). You can use accessor functions with d3.max() so something like

d3.max(yearsDate, (year) => {
  console.log(`year: ${year} new Date(year): ${new Date(year)}`);
  return year;
});

may provide some insight as you’ll see both values side by side in the console.

All speculation though without code. Put it in a codepen, comment the appropriate bits and post that and you might get a more definitive answer. It could be something wrong with the data or something else in the code causing the problem.

Thank you very much. I discovered my mistake:

  1. var xMax = d3.max(yearsDate) seems to return a reference to the max value and changing this value for the scale will therefore change the last value of yearsDate. Reason why the last bar was detached from the rest
  2. I needed to use var xMax = new Date(d3.max(yearsDate)) and then change xMax for the scale without modifying yearsDate.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.