Quirk
Quirk

Reputation: 175

d3 resummarise nested object

In my code I have taken the liberty of removing duplicated rows from a dataset using a d3.nest() function, output sample attached.

Now that I have unique entries in my JSON array I'd like to perform some calculations on this data set, specifically finding the mean 'cycle time' for each date. In this example the output ideally would look like:

[
  {
    "key": "2012-03",
    "values": [
      {
        "mean": 16,
      }
    ]
  },
  {
    "key": "2012-06",
    "values": [
      {
        "mean": 10,
      }
    ]
  },
  {
    "key": "2012-07",
    "values": [
      {
        "mean": 8,
      }
    ]
  }
]

I've tried following a few examples online but I seem to be missing something obvious, could someone please help?

var summaryTable = [
  {
    "key": "2012-03",
    "values": [
      {
        "key": "AAA-1",
        "value": {
          "cycletime": 14
        }
      },
      {
        "key": "AAA-2",
        "value": {
          "cycletime": 18
        }
      }
    ]
  },
  {
    "key": "2012-06",
    "values": [
      {
        "key": "AAA-3",
        "value": {
          "cycletime": 8
        }
      },
      {
        "key": "AAA-4",
        "value": {
          "cycletime": 12
        }
      }
    ]
  },
  {
    "key": "2012-07",
    "values": [
      {
        "key": "AAA-5",
        "value": {
          "cycletime": 15
        }
      },
      {
        "key": "AAA-5",
        "value": {
          "cycletime": 1
        }
      },
      {
        "key": "AAA-6",
        "value": {
          "cycletime": 8
        }
      }
    ]
  }
]

var d3Table = d3.nest()
    .key(function(d) { return d['key']; })
    .rollup(function(d) { 
        return {
                "medianCycleTime": d3.mean(d, d3.values(d['values']['value'])),
        };
    })
    .entries(summaryTable);

Upvotes: 1

Views: 54

Answers (1)

rioV8
rioV8

Reputation: 28633

After careful inspection of your d3.nest data I found the function to use in the rollup.

The argument d of the rollup is an array with all the objects that have that key. You have to index that first otherwise you get the values() method of the Array class.

var d3Table = d3.nest()
    .key(function(d) { return d['key']; })
    .rollup(function(d) {
        return { 
            "medianCycleTime": d3.mean(d[0]['values'], d => d.value.cycletime ),
        };
    })
    .entries(summaryTable);

Upvotes: 2

Related Questions