Search code examples
d3.jscounttype-conversionnestrollup

D3: converting from string to number with unary + sign is not working


I have a CSV file that I have imported. after import, I have used nest and rollup to organize the data like below.

      var data_group = d3.nest()
                      .key(function(d) {return +d.year;})
                      .key(function(d) {return +d.average_rating;})
                      .rollup(function (count) {
                        return count.length;
                      })
                      .entries(data);

      console.log(data_group) 

However, when I look at the console.log, the year and the the average_rating are strings. I would like them to be a number. How can I achieve this? Below is a picture of the output. Also, can someone explain why they are not numbers after the + sign? enter image description here


Solution

  • This is exactly as expected, as described in the d3.nest documentation. It also states explicitly in the documentation of nest.key that "The key function ... must return a string identifier".

    The first few lines of the example given there look like so:

    [{key: "1931", values: [
       {key: "Manchuria", values: [
       {yield: 27.00, variety: "Manchuria", year: 1931, site: "University Farm"},
       {yield: 48.87, variety: "Manchuria", year: 1931, site: "Waseca"},
    ...
    

    In particular, note that the first line starts key: "1931", even though 1931 is an integer value in the input data. That 1931 appears as an integer in the result only when it's a value, as in the lat two lines.

    It's probably also worth pointing out that d3.nest is long since deprecated and was even removed in V6 several years ago. You should seriously consider using d3.group and/or d3.rollup in V7.