Search code examples
javascriptd3.js

d3.rollup returns blank object


Below is the sample JSON trying to pass it to d3.rollup

const data = [ { "date": "2000-01-01", "name": "Coca-Cola", "category": "Beverages", "value": 72537 }, { "date": "2000-01-01", "name": "Microsoft", "category": "Technology", "value": 70196 }, { "date": "2000-01-01", "name": "IBM", "category": "Business Services", "value": 53183 } ]

below is my func :

populateDateValues() { datevalues = Array.from(d3.rollup(data, ([d]) => d.value, d => +d.date, d => d.name)) .map(([date, data]) => [new Date(date), data]) .sort(([a], [b]) => d3.ascending(a, b)) }

it is returning :

[[null,{}]]

trying to pass value into d3.rollup() and not receiving the expected value


Solution

  • Made some adjustments and getting the output some minor syntactical errors were there like function was not defined and dateValue datatype was also not defined here is the fix hope it works :

    import * as d3 from 'd3';
    
    const data = [
        // ... (your data objects)
      {
        "date": "2000-01-01",
        "name": "Coca-Cola",
        "category": "Beverages",
        "value": 72537
    }, {
        "date": "2000-01-01",
        "name": "Microsoft",
        "category": "Technology",
        "value": 70196
    }, {
        "date": "2000-01-01",
        "name": "IBM",
        "category": "Business Services",
        "value": 53183
    }
    ];
    
    function populateDateValues() {
        const dateValues = Array.from(
            d3.rollup(
                data,
                group => d3.sum(group, d => d.value),
                d => d.date,
                d => d.name
            )
        ).map(([date, value]) => [new Date(date), value])
        .sort(([a], [b]) => d3.ascending(a, b));
    
        return dateValues;
    }
    
    
    // Call the function and store the result
    const result = populateDateValues();
    console.log(result);

    This is the output which you will get :

    [
      [
        2000-01-01T00:00:00.000Z,
        InternMap(3) [Map] {
          'Coca-Cola' => 72537,
          'Microsoft' => 70196,
          'IBM' => 53183
        }
      ]
    ]