Home > Mobile >  How to pass keys as a list of strings to D3 group?
How to pass keys as a list of strings to D3 group?

Time:09-26

The d3.group documentation says:

d3.group(iterable, ...keys)

For example, if I have the following:

data = [
  {name: "jim",   amount: "34.0",   date: "11/12/2015"},
  {name: "carl",  amount: "120.11", date: "11/12/2015"},
  {name: "stacy", amount: "12.01",  date: "01/04/2016"},
  {name: "stacy", amount: "34.05",  date: "01/04/2016"}
]

But instead of:

d3.group(data, d => d.name, d => d.date)

I want to do something like:

d3.group(data, ['name', 'date'])

How should I do it? The reason is that I might not know the keys in advance and will have to do the grouping programatically.

Thank you!

CodePudding user response:

...keys can be a map which itself returns a function e.g. ...keys.map(k => d => d[k]).

See below - this uses groups instead of group as it's readable in the console output - but this works for group as well.

const data = [
  {name: "jim",   amount: "34.0",   date: "11/12/2015"},
  {name: "carl",  amount: "120.11", date: "11/12/2015"},
  {name: "stacy", amount: "12.01",  date: "01/04/2016"},
  {name: "stacy", amount: "34.05",  date: "01/04/2016"}
];

const keys = ["name", "date"];

const grps = d3.groups(
  data,
  ...keys.map(k => d => d[k])
);

console.log(grps);
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/7.6.1/d3.min.js"></script>

  • Related