d3/d3-array

d3.index(iterable, …keys)?

mbostock opened this issue · 2 comments

Sometimes you want something like d3.group, but with the expectation that there will be a single value rather than multiple values per unique key. You can do this using d3.rollup as

d3.rollup(data, ([d]) => d, d => d.foo, d => d.bar)

but this is a little verbose, and it will silently ignore additional values if the keys happen to be non-unique. So how about a stricter shorthand?

d3.index(data, d => d.foo, d => d.bar)

Where:

function index(values, ...keys) {
  return nest(values, identity, indexReduce, keys);
}

function indexReduce(values) {
  if (values.length !== 1) throw new Error("non-unique key");
  return values[0];
}

Is d3.index too generic a name? Maybe d3.groupUnique?

(See also the previous d3.uniques proposal #118.)

Fil commented

Maybe the word could be smth like "associate" or "dict / dictionary".

(I tend to rollup with v => v.pop().)