Skip to content

nestGroups

Recursively groups data by each key function, producing {key, values} objects compatible with d3-hierarchy.

Groups rows by the value each accessor returns, producing {key, values} entries in first-seen order. One accessor gives one level.

import {nestGroups} from "@d3plus/data";

const data = [
  {region: "North", year: 2023, sales: 120},
  {region: "North", year: 2024, sales: 135},
  {region: "South", year: 2023, sales: 80},
  {region: "South", year: 2024, sales: 95},
];

nestGroups(data, [d => d.region]);

With no accessors the rows come back untouched, so a caller can pass whatever depth of groupBy it has without special-casing zero.

import {nestGroups} from "@d3plus/data";

const data = [
  {region: "North", year: 2023, sales: 120},
  {region: "North", year: 2024, sales: 135},
  {region: "South", year: 2023, sales: 80},
  {region: "South", year: 2024, sales: 95},
];

nestGroups(data, []);

Each additional accessor nests another level inside the previous one, which is the shape d3-hierarchy expects and what a chart builds from a multi-key groupBy.

import {nestGroups} from "@d3plus/data";

const data = [
  {region: "North", year: 2023, sales: 120},
  {region: "North", year: 2024, sales: 135},
  {region: "South", year: 2023, sales: 80},
  {region: "South", year: 2024, sales: 95},
];

nestGroups(data, [d => d.region, d => d.year]);

Parameters

import {nestGroups} from "@d3plus/data";
datarequiredArray.<DataPoint>

The flat data array to nest.

fnsrequiredArray.<KeyAccessor>

An array of key accessor functions, one per nesting level.