Skip to content
This repository has been archived by the owner on Nov 11, 2018. It is now read-only.

d3.group convenience function? #12

Closed
mbostock opened this issue Dec 7, 2016 · 3 comments
Closed

d3.group convenience function? #12

mbostock opened this issue Dec 7, 2016 · 3 comments

Comments

@mbostock
Copy link
Member

mbostock commented Dec 7, 2016

Sometimes it’s convenient to group an array by a single key. You can do that using d3.nest like so:

var entries = d3.nest()
    .key(d => d.foo)
    .entries(data);

Is it worth making a convenience function for this?

d3.group = function(array, key) {
  return d3.nest().key(key).entries(array);
};

I guess it would violate the parsimony principle.

@geekplux
Copy link

d3.group is more semantic.

@1wheel
Copy link

1wheel commented Mar 22, 2017

We've been using nestBy

d3.nestBy = function(array, key){
  return d3.nest()
    .key(key)
    .entries(array)
    .map(function(d){
      d.values.key = d.key
      return d.values
    })
}

Not having to type values a zillion times is nice since I use them so much. I typically manually add multiple levels of nesting and mutate with a forEach loop instead of using sort, rollup or multiple key calls:

var byCountry = d3.nestBy(data, d => d.country)
byCountry.forEach(d => {
  d.sort(d3.ascendingKey(d => d.year))
  d.byYear = d3.nestBy(d, d => d.year)
  d.byYear.forEach((year, i) => {
    var cumulativePercent = 0
    year.sort(d3.ascendingKey(d => d.isRight ? 0 : d.isCenter: 2 : 1))
      .forEach(d => {
        cumulativePercent += d.percent
        d.cumulativePercent = cumulativePercent
      })
  })
})

The ends up being a bit longer and not nearly as pretty, but is easier to incrementally experiment with different subgrouping and summary statistics while exploring different forms.

@mbostock
Copy link
Member Author

Moving discussion over to d3/d3-array#75.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Development

No branches or pull requests

3 participants